Mysql Order / Sort by before Group by

Submitted by n8coder on Sun, 08/30/2009 - 20:14

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 `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.