Page is a not externally linkable
- Code, Content, and Presentation
-- Databases
---- How to group by one field and order by another?


MichaelBluejay - 5:30 pm on Oct 3, 2012 (gmt 0)


I'm trying to pull the most recent posts out of a table, but have each topic represented only once.

This gets the posts, but takes more than one from each topic:
SELECT topic_id,posted,poster,message FROM posts ORDER BY posted DESC LIMIT 20


Adding a GROUP BY makes sure each thread is represented only once, but then I no longer get the most recent post from each topic:
SELECT topic_id,posted,poster,message FROM posts GROUP BY topic_id ORDER BY posted DESC LIMIT 20


I tried to put "ORDER BY" before "GROUP BY", but that just gives me a syntax error:
SELECT topic_id,posted,poster,message FROM posts ORDER BY posted DESC LIMIT 20[ GROUP BY topic_id


How should I write my query?


Thread source:: http://www.webmasterworld.com/databases_sql_mysql/4503580.htm
Brought to you by WebmasterWorld: http://www.webmasterworld.com