MySQL中的顺序为0,null,常规数字

时间:2016-11-18 00:19:21

标签: mysql sql

我的价值观如下:

ID  
0  
NULL  
NULL  
2  
0  
3  

尝试获取查询排序顺序,使其显示如下:

2  
3  
0  
0  
NULL  
NULL  

感谢任何帮助

1 个答案:

答案 0 :(得分:1)

您可以使用IF语句强制执行逻辑,然后在底部使用空值。在列名前面加一个减号( - )来排序空值。

测试案例

CREATE TABLE mytable (a int);

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

<强>结果

SELECT *, IF (a = 0 OR a = NULL, NULL, a) as sort_order
FROM mytable
ORDER BY -sort_order DESC
+------+
| a    |
+------+
|    1 |
|    2 |
|    3 |
|    4 |
|    5 |
|    0 |
|    0 |
|    0 |
| NULL |
| NULL |
| NULL |
+------+

http://sqlfiddle.com/#!9/58b399/14