我想按字母顺序返回一个项目列表,但是将“空”结果附加到结尾而不是出现在开头。有没有办法使用MySQL ORDER语句,或者另一种方式?
SELECT * FROM persons WHERE status = 'active' ORDER BY lastName;
我得到了什么:
Jason
Peter
Frank Asimov
Reda Banks
Scott Sorrel
我想要的是什么:
Frank Asimov
Reda Banks
Scott Sorrel
Jason
Peter
答案 0 :(得分:1)
SELECT * FROM persons WHERE status = 'active'
ORDER BY case when ifnull(lastName,'') = '' then 1 else 0 end, lastname
答案 1 :(得分:0)
您可以使用FIELD语句执行此操作。它就是这样的:
SELECT [...] ORDER BY FIELD(lastName, '') DESC
这将把所有空字符串的姓氏附加到结尾。如果不是空字符串,则数据库上为NULL:
SELECT [...] ORDER BY FIELD(lastName, NULL) DESC;
答案 2 :(得分:-1)
我相信你所需要的只是ORDER BY
firstName
:
SELECT * FROM persons WHERE status = 'active' ORDER BY lastName, firstName