仅使用sql(MySQL)我想选择父子关系的最后一个子行,其中子行按时间戳排序.
例如,使用表发票和invoice_items,我想分别为每个发票的最新(即:最近时间戳)invoice_items记录.
--------------------------
|Invoices |
--------------------------
|invoice_id| other fields|
--------------------------
| 1 | ... |
--------------------------
| 2 | ... |
--------------------------
| 3 | ... |
--------------------------
--------------------------------------------
|Invoice_Items |
--------------------------------------------
| id | invoice_id | invoice_item_timestamp |
--------------------------------------------
| 1 | 1 | 2009-12-01 10:00:00 |
--------------------------------------------
| 2 | 1 | 2009-12-01 10:01:00 |
--------------------------------------------
| 3 | 1 | 2009-12-01 10:02:00 |
--------------------------------------------
| 4 | 2 | 2009-12-01 9:00:00 |
--------------------------------------------
| 5 | 3 | 2009-12-02 08:30:00 |
--------------------------------------------
| 6 | 3 | 2009-12-03 08:31:00 |
--------------------------------------------
-----------------------------------------------------
|invoice_id| invoice_item_id |invoice_item_timestamp|
---------------------------------------------------
| 1 | 3 | 2009-12-01 10:02:00 |
| 2 | 4 | 2009-12-01 09:00:00 |
| 3 | 6 | 2009-12-03 08:31:00 |
-----------------------------------------------------
最佳答案
SELECT i.*,it.*
FROM invoices i
INNER JOIN (
SELECT invoice_id,MAX(invoice_item_timestamp)
FROM invoice_items
GROUP BY invoice_id
) it ON (i.invoice_id=it.invoice_id)