MySQL - 如何按名称 a 到 z 排序但将空名称放在底部?

MySQL - how to order by name a to z but put empty name on the bottom?

我在 table 中有名字、姓氏、手机。在滚动列表中用 "firstname lastname"

表示
SELECT * FROM `sh_contact` order by firstname asc;

但有些行包含空名字,因此滚动列表显示为空 " lastname".

以避免用户界面混乱。如何将所有非空名字放在顶部并在末尾显示空名字?

您可以使用多个密钥:

order by (case when firstname = '' or firstname is null then 1 else 2 end) desc,
         firstname asc

试试这个:

...
order by firstname is null, firstname

这是有效的,因为在 MySQL 中,为真的布尔表达式为 1,为假的为 0,因此按此排序会将所有空名字放在最后。

如果您想将空白视为空值,请使用:

...
order by coalesce(firstname, '') = '', firstname

或者如果 firstname 永远不会为 null,则更简单:

...
order by firstname = '', firstname

这应该有效:

SELECT * FROM `sh_contact` ORDER BY CASE WHEN firstname = '' THEN 2 ELSE 1 END, firstname

DB Fiddle