Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ORDER BY date and time BEFORE GROUP BY name in mysql

i have a table like this:

name    date         time tom | 2011-07-04 | 01:09:52 tom | 2011-07-04 | 01:09:52 mad | 2011-07-04 | 02:10:53 mad | 2009-06-03 | 00:01:01 

i want oldest name first:

SELECT *  ORDER BY date ASC, time ASC  GROUP BY name 

(->doesn't work!)

now it should give me first mad(has earlier date) then tom

but with GROUP BY name ORDER BY date ASC, time ASC gives me the newer mad first because it groups before it sorts!

again: the problem is that i can't sort by date and time before i group because GROUP BY must be before ORDER BY!

like image 778
CodingYourLife Avatar asked Jul 04 '11 13:07

CodingYourLife


People also ask

Can I do ORDER BY before GROUP BY?

When combining the Group By and Order By clauses, it is important to bear in mind that, in terms of placement within a SELECT statement: The GROUP BY clause is placed after the WHERE clause. The GROUP BY clause is placed before the ORDER BY clause.

Can you use both GROUP BY and ORDER BY?

GROUP BY and ORDER BY are two different things. It is plain wrong that you cannot use them together. GROUP BY is used to tell the DBMS per which group to aggregate the data. In your example you sum gallons per colorComp and colorID .

Does ORDER BY affect GROUP BY?

No, the order doesn't matter for the GROUP BY clause. MySQL and SQLite are the only databases I'm aware of that allow you to select columns which are omitted from the group by (non-standard, not portable) but the order doesn't matter there either.

Does WHERE run before GROUP BY?

Yes it does. Perfect, so knowing that the where clause will maximum return 3 records does not de-perform due to the order by clause.


2 Answers

Another method:

SELECT *  FROM (     SELECT * FROM table_name     ORDER BY date ASC, time ASC  ) AS sub GROUP BY name 

GROUP BY groups on the first matching result it hits. If that first matching hit happens to be the one you want then everything should work as expected.

I prefer this method as the subquery makes logical sense rather than peppering it with other conditions.

like image 153
swbeeton Avatar answered Sep 19 '22 00:09

swbeeton


As I am not allowed to comment on user1908688's answer, here a hint for MariaDB users:

SELECT * FROM (      SELECT *      ORDER BY date ASC, time ASC      LIMIT 18446744073709551615      ) AS sub GROUP BY sub.name 

https://mariadb.com/kb/en/mariadb/why-is-order-by-in-a-from-subquery-ignored/

like image 23
Vincent Avatar answered Sep 19 '22 00:09

Vincent