仅使用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 |
--------------------------------------------
生成结果集的最佳SQL语法是什么,看起来像下表?
-----------------------------------------------------
|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)
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|