2011-09-15 15 views
2

previous posterと同様の質問です。最後の行がMySQLを使用して条件に一致する親子関係の最後の子行を選択する方法

質問:「MySQLを使用して、子行がタイムスタンプで順序付けされている親子関係の最後の子行をそれぞれ選択したいと思います。

私はこれをやりたい、しかし私はまたstatus 1.

私のテーブルがfobs_inventoryfobs_inventory_historyあるのみ子行を選択したいと思います。次の表のようになります。結果セットを生成するための最良のSQL構文は何fobs_inventory_history.status = 1

------------------------------- 
| fobs_inventory    | 
------------------------------- 
| inv_id | other fields  | 
------------------------------- 
| 1  | ...    | 
| 2  | ...    | 
| 3  | ...    | 
------------------------------- 

---------------------------------------------- 
| fobs_inventory_history      | 
---------------------------------------------- 
| id | inv_id | status | created_at   | 
---------------------------------------------- 
| 1 | 1  | 0  | 2011-10-11 10:00:00 | 
| 2 | 1  | 1  | 2011-08-01 10:00:00 | 
| 3 | 1  | 0  | 2011-07-01 10:00:00 | 

| 4 | 2  | 1  | 2011-09-11 14:00:00 | 
| 5 | 2  | 0  | 2011-08-01 12:00:00 | 
| 6 | 2  | 2  | 2011-07-01 00:00:00 | 

| 7 | 3  | 1  | 2011-10-11 14:00:00 | 
| 8 | 3  | 2  | 2011-08-01 12:00:00 | 
| 9 | 3  | 0  | 2011-07-01 00:00:00 | 
---------------------------------------------- 

fobs_inventoryについてfobs_inventory_historyレコード:私は、最新(直近タイムスタンプIE)をしたいですか?

-------------------------------------------------------------------- 
| inv_id | fob_inventory_history_id | status | created_at   | 
-------------------------------------------------------------------- 
| 2  | 4      | 1  | 2011-09-11 14:00:00 | 
| 3  | 7      | 1  | 2011-10-11 14:00:00 | 
-------------------------------------------------------------------- 

私はstatus編集

1の

もう少しこの上で働いた後、最新のタイムスタンプが持っている行のみを返したいが、私が思い付きましたそれは同じことをやろうとしている誰かを助けるかもしれないので、私がここに投稿している解決策です。副選択の外によって本質的解決にはMAX(関連付けられているすべての対応するフィールドを選択した

)とGROUP、それをチェックアウト:

select h.id, h.fob_id, h.inv_id, h.status, h.created_at from fobs_inventory_history h, (
    select id, inv_id, status, max(created_at) as ts 
    from fobs_inventory_history 
    group by inv_id 
) h2 
where h.created_at = h2.ts 
and h.inv_id = h2.inv_id 
and h.fob_id = 1 and h.status = 1 

答えて

0

select 
    inv_id, id AS fob_inventory_history_id, status, created_at from fobs_inventory_history 
where 
    status = 1 
order by created_at desc 
LIMIT 2 

を試してみてくださいあなたが変更することができます取得する行の数に基づいて制限する

1

ありがとうございました!私が2日間立ち往生したという問題を解決しました。 親情報を追加する必要があったので、次のようにこのクエリにJOINを追加しました:

select i.custid, i.custorderno, h.id, h.fob_id, h.inv_id, h.status, h.created_at from fobs_inventory_history h, (
    select id, inv_id, status, max(created_at) as ts 
    from fobs_inventory_history 
    group by inv_id 
) h2 
INNER JOIN invoice AS i ON h2.inv_id = i.inv_id 
where h.created_at = h2.ts 
and h.inv_id = h2.inv_id 
and h.fob_id = 1 and h.status = 1 
関連する問題