Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select the last child row of a parent/child relationship using SQL

Tags:

sql

mysql

Using SQL (MySQL) only I would like to select each of the last child rows of a parent child relationship where the child rows are ordered by a timestamp.

For example using the tables invoices and invoice_items, I want the newest (ie: most recently timestamped) invoice_items records for each invoice respectively.

--------------------------
|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  |
--------------------------------------------    

What is the best SQL syntax to produce a resultset that would look something like the following table?

-----------------------------------------------------
|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  |
-----------------------------------------------------
like image 890
rswolff Avatar asked Dec 17 '09 22:12

rswolff


2 Answers

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)
like image 95
Patrick Avatar answered Sep 29 '22 00:09

Patrick


I don't use MySQL, but you'll get the idea:

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)

... assuming there are no duplicates of invoice_item_id and invoice_id in the invoice_item table.

like image 20
cdonner Avatar answered Sep 28 '22 23:09

cdonner