How to output items in Order in MySQL?
I have a column called "menu_order" which has no default value. When I select the contents of this column using the following select statement:
SELECT * FROM categories ORDER BY menu_order ASC
It lists the category items that have nothing as their menu order first and then the one's that have 1's and 2's and 3's. Is there any way to prevent SQL from take nothing to come before numbers when I am trying to list things in order?
So for example, if I have:
cat_name | menu_order
----------------------
Lunch | 1
Dinner |
And I perform开发者_JAVA技巧 my query, the output should be:
Lunch Dinner
Not:
Dinner Lunch
This will put the null values last:
SELECT *
FROM categories
ORDER BY menu_order IS NULL ASC, menu_order ASC
You can use the IFNULL function in the order by with a large number
ORDER BY IFNULL(menu_order, 1000) ASC
You can even try using a case statement
ORDER BY
CASE
WHEN menu_order IS NULL THEN 1
ELSE 0
END ASC,
menu_order ASC
ORDER BY IFNULL(menu_order, 99999999) ASC
精彩评论