按最大数字递减排序,但空排名更高

时间:2012-07-11 18:40:37

标签: mysql

我有这个问题:

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,我想要那一行。

我应该如何修改查询呢?

提前致谢!

2 个答案:

答案 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;