Skip to content

Instantly share code, notes, and snippets.

@abedsujan
Last active December 11, 2015 17:18
Show Gist options
  • Save abedsujan/4633509 to your computer and use it in GitHub Desktop.
Save abedsujan/4633509 to your computer and use it in GitHub Desktop.
MySQL – left join on last (or first) record in the right table
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