2011-09-15 18 views
2

我的問題類似於previous poster如何選擇最後一行與使用MySQL的條件匹配的父/子關係的最後一個子行

他的問題是:「僅使用MySQL我想選擇父子關係的最後一個子行,其中子行按時間戳排序」。

我想做到這一點,但是我也想只選擇子行,其中status爲1

我的表是fobs_inventoryfobs_inventory_history。我想最新的(即:最近的時間戳)fobs_inventory_history記錄每個fobs_inventory,其中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 | 
---------------------------------------------- 

什麼是最好的SQL語法來產生一個結果,將看起來如下表樣的?

-------------------------------------------------------------------- 
| 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 | 
-------------------------------------------------------------------- 

我想爲它最近的時間戳必須返回只有那些行更多關於這方面的一些工作1.編輯

一個status

後,我想出了我在這裏發佈的解決方案,因爲它可能會幫助別人試圖做同樣的事情。

本質上的解決辦法是選擇)由子查詢外與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

非常感謝你張貼這個!它解決了我被困兩天的問題。 我需要包含一些父母信息,所以我添加了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 
相關問題