My table looks like this (and I'm using MySQL):
m_id | v_id | timestamp
------------------------
6 | 1 | 1333635317
34 | 1 | 1333635323
34 | 1 | 1333635336
6 | 1 | 1333635343
6 | 1 | 1333635349
My target is to take each m_id one time, and order by the highest timestamp.
The result should be:
m_id | v_id | timestamp
------------------------
6 | 1 | 1333635343
34 | 1 | 1333635336
And i wrote this query:
SELECT * FROM table GROUP BY m_id ORDER BY timestamp DESC
But, the results are:
m_id | v_id | timestamp
------------------------
34 | 1 | 1333635323
6 | 1 | 1333635317
I think it causes because it first does GROUP_BY and then ORDER the results.
Any ideas? Thank you.
MAX
to select the max from your group – Nanne Apr 5 '12 at 14:45GROUP BY
clause with no aggregate function (eg:COUNT(), SUM(), MAX()
) makes no sense at all. It baffles me that MySQL even allows this. Think about it, why are you grouping if you don't do anything with the groups? – NullUserException Apr 5 '12 at 14:47ORDER BY
must influence only results ofGROUP BY
, not data before grouping. – Timur Apr 5 '12 at 14:59GROUP BY
without an aggregate function is to group by the primary key. Useful where your joins yield 1:manySELECT a.id, a.name, a.age, MAX(b.savings) FROM a INNER JOIN b on a.id = b._id GROUP BY a.id
– MatBailie Apr 5 '12 at 15:35