我有一张这样的表:
// 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()
个功能,type
和post_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 |
+-----------+-------+---------+------+
答案 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