仅使用SQL(MySQL)我想选择父子关系的每个子行,其中子行按时间戳排序。
例如,使用表invoices
和invoice_items
,我希望分别为每个invoice_items
提供最新的(即:最近时间戳)invoice
条记录。
--------------------------
|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 |
-----------------------------------------------------
答案 0 :(得分:14)
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)
答案 1 :(得分:1)
我不使用MySQL,但你会明白这个想法:
select
invoices in
inner join invoice_items it
on in.invoice_id = it.invoice_id
and invoice_item.invoice_item_id =
(select max(invoice_item_id) from invoice_item
where invoice_id = in.invoice_id)
...假设invoice_item表中没有invoice_item_id和invoice_id的重复。
答案 2 :(得分:0)
我认为这样的事情会奏效:
select i.invoice_id, ii.id, ii.invoice_item_timestamp from invoices i left join invoice_items ii on ii.invoice_id = i.invoice_id
where ii.invoice_item_timestamp =
(select max(ii2.invoice_item_timestamp) from invoice_items ii2 where ii2.invoice_id = ii.invoice_id)
答案 3 :(得分:-1)
你可以试试这个(未经测试):
SELECT a.*
FROM Invoices a, invoice_items b
WHERE a.invoice_id = b.invoice_id
ORDER BY invoice_item_timestamp DESC
LIMIT 1