0

我有这个查询:

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排名高于任何数字。所以如果NULL在suspension_expireson中有一行值,我想要那个。

我应该如何修改查询来做到这一点?

提前致谢!

4

2 回答 2

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;
于 2012-07-11T18:43:49.853 回答
0

这将首先对所有 NULL 值进行排序,然后按降序对非 NULL 值进行排序。

ORDER BY case when suspension.suspension_expireson is null then 0 else 1 end, suspension.suspension_expireson DESC LIMIT 1;
于 2012-07-11T18:43:28.437 回答