Sunday, February 19, 2012

Mysql Order / Sort by before Group by


Every developer knows the horror of mysql sort/order by or select distinct using with group by. Mysql does group by before order by and you get mixed results not what you expected. This is a small solution with less performance problem:
SELECT * FROM 

(
select * from `my_table` order by timestamp desc
) as my_table_tmp

group by catid

order by nid desc
In this example we get latest news in each category. We create a temp table by sorting by timestamp and group by after it. It worked for me.