我有这个问题:
SELECT user.user_id,
user.user_name,
user.user_hash,
suspension.suspension_expireson
FROM user
LEFT JOIN suspension
ON suspension.suspension_user = user.user_id
WHERE user.user_name = "tester"
ORDER BY suspension.suspension_expireson DESC
LIMIT 1;
它命令suspension_expireson
以便最高数字(它是unixtime,因此将来最远)出现,但我希望NULL
排名高于任何数字。因此,如果在suspension_expireson中有一行值NULL
,我想要那一行。
我应该如何修改查询呢?
提前致谢!
答案 0 :(得分:2)
在CASE
中使用ORDER BY
语句为空值0提供一个较低的常量值,而不是其他行,得到1. 0在1之前排序,然后其余排序(1)由suspension_expireson DESC
订购。
SELECT
user.user_id,
user.user_name,
user.user_hash,
suspension.suspension_expireson
FROM
user
LEFT JOIN suspension ON suspension.suspension_user = user.user_id
WHERE user.user_name = "Tester"
ORDER BY
CASE WHEN suspension_expireson IS NULL THEN 0 ELSE 1 END,
suspension.suspension_expireson DESC
LIMIT 1;
答案 1 :(得分:0)
这将首先对所有NULL值进行排序,然后按降序对非NULL值进行排序。
ORDER BY case when suspension.suspension_expireson is null then 0 else 1 end, suspension.suspension_expireson DESC LIMIT 1;