我的問題類似於previous poster。如何選擇最後一行與使用MySQL的條件匹配的父/子關係的最後一個子行
他的問題是:「僅使用MySQL我想選擇父子關係的最後一個子行,其中子行按時間戳排序」。
我想做到這一點,但是我也想只選擇子行,其中status
爲1
我的表是fobs_inventory
和fobs_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