即使值不存在,也需要选择一行

时间:2014-01-27 16:02:04

标签: sql

我需要为每个用户获得特定game_id的最高分数:

表'得分'

----------------------
|uid |game_id |score |
----------------------
|1   |0       |0     |
|2   |0       |0     |
|1   |0       |1     |
|1   |0       |2     |
|2   |1       |0     |
|2   |1       |3     |
|2   |1       |5     |
----------------------

我需要这个输出(对于game_id = 1):

-------------
|uid |score |
-------------
|1   |      |
|2   |5     |
-------------

正如您所看到的,用户1没有game_id 1的条目,但我还是要让他回来......

任何帮助都非常感谢!

2 个答案:

答案 0 :(得分:2)

您可以使用条件聚合执行此操作:

select uid, max(case when game_id = 1 then score end) as game1max
from scores
group by uid;

答案 1 :(得分:0)

您可以使用自引用左连接执行此操作:

SELECT s1.uid, MAX(s2.score) MaxSCore
FROM scores s1
LEFT JOIN scores s2
  ON s1.uid = s2.uid
     AND game_id = 1
GROUP BY s1.uid

或子查询:

SELECT DISTINCT 
    s1.uid, 
    (SELECT MAX(s2.score) 
     FROM scores s2
     WHERE s1.uid = s2.uid
        AND game_id = 1) MaxScore
FROM scores s1