如何将NULL视为最小值?

时间:2016-08-31 23:41:14

标签: mysql sql sql-order-by

我有一张这样的表:

// notifications
+----+-----------+-------+---------+---------+------+
| id |   score   | type  | post_id | user_id | seen |
+----+-----------+-------+---------+---------+------+
| 1  | 15        | 1     | 2342    | 342     | 1    |
| 2  | 5         | 1     | 2342    | 342     | 1    |
| 3  | NULL      | 2     | 5342    | 342     | 1    |
| 4  | -10       | 1     | 2342    | 342     | NULL |
| 5  | 5         | 1     | 2342    | 342     | NULL |
| 6  | NULL      | 2     | 8342    | 342     | NULL |
| 7  | -2        | 1     | 2342    | 342     | NULL |
+----+-----------+-------+---------+---------+------+
-- type: 1 means "it is a vote", 2 means "it is a comment (without score)"

这是我的问题:

SELECT SUM(score), type, post_id, seen
FROM notifications
WHERE user_id = 342
GROUP BY type, post_id
ORDER BY (seen IS NULL) desc

如您所见,有SUM()个功能,typepost_id列都在GROUP BY语句中。那我现在谈论seen专栏。我不想把它放到GROUP BY声明中。所以我必须使用MAX()MIN()。正确?

实际上,如果有一行NULL,我需要选择seen作为seen = NULL(在上面的查询中)。即使我使用1,我当前的查询也会将seen选为MIN(seen)的值。那么,当1时,为什么NULL最小?

此外,我想订购行,以便所有SEEN = NULL都位于列表顶部。我怎么能这样做?

预期结果:

// notifications
+-----------+-------+---------+------+
|   score   | type  | post_id | seen |
+-----------+-------+---------+------+
| 13        | 1     | 2342    | NULL |
| NULL      | 2     | 8342    | NULL |
| NULL      | 2     | 5342    | 1    |
+-----------+-------+---------+------+

2 个答案:

答案 0 :(得分:2)

你可以这样做

   case when sum(seen is null) > 0 
        then null 
        else min(seen)
   end

答案 1 :(得分:1)

您可以使用以下查询:

SELECT SUM(score), type, post_id, min(IFNULL(seen, 0)) as seen
FROM notifications
WHERE user_id = 342
GROUP BY type, post_id
ORDER BY seen desc