如何使用SQL选择父/子关系的最后一个子行

前端之家收集整理的这篇文章主要介绍了如何使用SQL选择父/子关系的最后一个子行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

仅使用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)
原文链接:https://www.f2er.com/mysql/433841.html

猜你在找的MySQL相关文章