Latest |Kites |Pictures |Programming |Life
[filed under Programming]MySQL max of two columns

How to get the MAX or MIN value of two columns: GREATEST( col_1, col_2 )

Or a more interesting example. I have a client who may have some reports. I need to list the clients in 'most recently active' order. So if they have had a recent action they should be near the top of the list, or if they have recently had a report they should be near the top of the list:

SELECT clients.id, clients.name, clients.date, MAX(r.date), GREATEST(clients.date, IFNULL(MAX(r.date), clients.date)) AS date
FROM clients
LEFT JOIN reports r on r.clients_id=clients.id
GROUP BY clients.id
ORDER BY date DESC

So this uses MAX to get the most recent report (this may return NULL if they have no reports) then I use GREATEST to choose the most recent of the two dates (two columns). Job done.

 

11th of August, 2008@4:54:51 PM
add a comment, permanent link to article

Comments

Check this if you are a human being. Thanks. (I'm trying to reduce my comment spam :-)

Comment

Server Grind [0.0022 seconds]