MySQL:按字段排序,在末尾放置空单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5825804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 19:42:04  来源:igfitidea点击:

MySQL: Order by field, placing empty cells at end

mysqlsorting

提问by BenM

I have a MySQL table which contains a number of products. What I want to do is sort the table by one particular column (most of the values begin with numbers for example: 1st, 2nd), etc. However, since some records do not have a value for this column, when I try to sort, the table automatically puts empty rows FIRST.

我有一个包含许多产品的 MySQL 表。我想要做的是按一个特定的列对表进行排序(大多数值以数字开头,例如:1st、2nd)等。但是,由于某些记录没有该列的值,当我尝试排序时,表自动将空行放在首位。

I am looking for a way to sort the row ASCENDING, but only insert blank records at the end of the sorted records, if that makes sense?

我正在寻找一种对行 ASCENDING 进行排序的方法,但只在排序记录的末尾插入空白记录,如果这有意义吗?

Any help would be most gratefully received!

任何帮助将不胜感激!

回答by Nicola Cossu

select * from table
order by if(field = '' or field is null,1,0),field

回答by Ahmad Vaqas Khan

This is one of the most effective method

这是最有效的方法之一

ASC Order

ASC 订单

SELECT * FROM user ORDER BY name IS NULL, name ASC

Expected Result:

预期结果:

+----+--------+------------+
| id |  name  | date_login |
+----+--------+------------+
|  3 |  david | 2016-12-24 |
|  2 |  john  | NULL       |
|  4 |  zayne | 2017-03-02 |
|  1 |  NULL  | 2017-03-12 |

DESC Order

DESC 订单

SELECT * FROM user ORDER BY name IS NULL, name DESC

Expected Result:

预期结果:

+----+--------+------------+
| id |  name  | date_login |
+----+--------+------------+
|  4 |  zayne | 2017-03-02 |
|  2 |  john  | NULL       |
|  3 |  david | 2016-12-24 |
|  1 |  NULL  | 2017-03-12 |