Last active
December 11, 2015 17:18
-
-
Save abedsujan/4633509 to your computer and use it in GitHub Desktop.
MySQL – left join on last (or first) record in the right table
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
http://murrayhopkins.wordpress.com/2008/10/28/mysql-left-join-on-last-or-first-record-in-the-right-table/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SELECT | |
customers.*, sale_tmp.* | |
FROM | |
customers | |
LEFT JOIN ( SELECT s1.* | |
FROM sales as s1 | |
LEFT JOIN sales AS s2 | |
ON s1.custID = s2.custID AND s1.saledate < s2.saledate | |
WHERE s2.custID IS NULL ) as sale_tmp | |
ON (customers.custID = sale_tmp.custID) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment