In my system, I have clients. Clients have programs. I want to display a list of clients, showing their most recent active (if it exists) program.
Thus, we have some
SELECT c.*, p.*
FROM clients AS c
JOIN programs AS p
ON p.id =
(
SELECT pi.id
FROM programs AS pi
WHERE pi.client_id = c.id
ORDER BY
pi.close_date=0 DESC, pi.close_date DESC
LIMIT 1
)
Thanx should go to @Quassnoi. See his answer in a similar (but more complicated) question: mysql-group-by-to-display-latest-result
If you update the programs
table and set close_date
for all records that it is zero to close_date='9999-12-31'
, then your ORDER BY
will be simpler (and the whole query faster with proper indexes):
ORDER BY
pi.close_date DESC
Try this order by clause ...
ORDER BY client.id, CASE WHEN program.close_date = 0 THEN 0 ELSE 1 END, program.close_date DESC