Sorting MySQL Tables by Two Columns
To order a MySQL table by two columns, you need to specify both sorting criteria in the ORDER BY clause, separated by commas. By default, sorting is in ascending order. To sort in descending order, use the DESC keyword.
Consider the following example: You have an articles table with columns named article_rating and article_time. To sort the table in descending order by rating, then in descending order by date, use the following query:
ORDER BY article_rating DESC, article_time DESC
This will result in articles with higher ratings appearing first, and within each rating group, articles with more recent dates will appear first.
For instance, if you had the following data in your articles table:
article_rating | article | article_time
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 query above would produce the following output:
article_rating | article | article_time
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
By specifying both sorting criteria in the ORDER BY clause, you can effectively order your table by multiple columns, ensuring the desired ordering of your data.
The above is the detailed content of How to Sort a MySQL Table by Two Columns?. For more information, please follow other related articles on the PHP Chinese website!