How do I sort a MySQL table by two columns?
What I want are articles sorted by highest ratings first, then most recent date. As an example, this would be a sample output (left # is the rating, then the article title, then the article date)
50 | This article rocks | Feb 4, 2009 35 | This article is pretty good | Feb 1, 2009 5 | This Article isn't so hot | Jan 25, 2009
The relevant SQL I'm using is:
ORDER BY article_rating, article_time DESC
I can sort by one or the other, but not both.
The following will order your data depending on both column in descending order.
DESC
at the end will sort by both columns descending. You have to specifyASC
if you want it otherwiseDefault sorting is ascending, you need to add the keyword DESC to both your orders:
This maybe help somebody who is looking for the way to sort table by two columns, but in paralel way. This means to combine two sorts using aggregate sorting function. It's very useful when for example retrieving articles using fulltext search and also concerning the article publish date.
This is only example, but if you catch the idea you can find a lot of aggregate functions to use. You can even weight the columns to prefer one over second. The function of mine takes extremes from both sorts, thus the most valued rows are on the top.
Sorry if there exists simplier solutions to do this job, but I haven't found any.
will sort by article_time only if there are two articles with the same rating. From all I can see in your example, this is exactly what happens.
but consider: