Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use an ORDER BY with a query that already has GROUP BY

I'm using MySQL and I have a table that has dates in a column (I'm making a table of due dates for a class). Previously I had the query as follows:

SELECT * FROM duedates_f2011 ORDER BY anothercolumn

In order to prevent duplicate occurrences (based on the duedate column) I had to change it as follows:

SELECT * FROM duedates_f2011 GROUP BY duedate

Currently, it's retained the same order, but how can I assure that it will still do so? Nothing in the GROUP BY tutorials I've read indicates that it will still sort it, and adding an ORDER BY statement afterwards is incorrect. Is there something I'm missing, or is there something else I should add to make sure it remains in order?

(as indicated in my tags, I'm using PHP to run the query)

like image 266
muttley91 Avatar asked Jan 19 '26 16:01

muttley91


2 Answers

SELECT * FROM duedates_f2011 GROUP BY duedate ORDER BY anothercolumn;

This is according to the MySQL manpages.

like image 195
Arjan Avatar answered Jan 21 '26 06:01

Arjan


How about selecting with a grouping first, then doing the order later, like this?

SELECT * FROM
   (SELECT * FROM duedates_f2011 GROUP BY duedate) a
ORDER BY anothercolumn

I don't see any reason for you to settle on it being ordered by the grouped column. Be bold! Demand more of your database! It should bow to your every whim!

mysql> SELECT Jump FROM YourDatabase;
+----------------+ 
| Jump           |
+----------------+
| How high?      |
+----------------+
1 row in set (0.00 sec)
like image 24
Chris Cunningham Avatar answered Jan 21 '26 05:01

Chris Cunningham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!