Using MySql, can I sort a column but have 0 come last?

♀尐吖头ヾ 提交于 2019-11-30 11:45:47

问题


I want to sort by an column of ints ascending, but I want 0 to come last. Is there anyway to do this in MySql?


回答1:


You may want to try the following:

SELECT * FROM your_table ORDER BY your_field = 0, your_field;

Test case:

CREATE TABLE list (a int);

INSERT INTO list VALUES (0);
INSERT INTO list VALUES (0);
INSERT INTO list VALUES (0);
INSERT INTO list VALUES (1);
INSERT INTO list VALUES (2);
INSERT INTO list VALUES (3);
INSERT INTO list VALUES (4);
INSERT INTO list VALUES (5);

Result:

SELECT * FROM list ORDER BY a = 0, a;

+------+
| a    |
+------+
|    1 |
|    2 |
|    3 |
|    4 |
|    5 |
|    0 |
|    0 |
|    0 |
+------+
8 rows in set (0.00 sec)



回答2:


You can do the following:

SELECT value, IF (value = 0, NULL, value) as sort_order
FROM table
ORDER BY sort_order DESC

Null values will be down of the list.




回答3:


The following query should do the trick.

(SELECT * FROM table WHERE num!=0 ORDER BY num) UNION (SELECT * FROM table WHERE num=0)



回答4:


SELECT * FROM your_table ORDER BY 0.1/your_field;


来源:https://stackoverflow.com/questions/3130197/using-mysql-can-i-sort-a-column-but-have-0-come-last

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!