MySQL内部加入/最大值/组

时间:2018-01-21 16:21:59

标签: mysql sql

道歉,如果这已经被覆盖,但我已经检查了许多其他问题,似乎无法得到我想要的结果。

SQL小提琴 http://www.sqlfiddle.com/#!9/d0a1f

我想要返回按类别分组的最高级别成就。因此虚拟数据将使用“Newbie Leveler”和“业余银行家”返回行

SELECT 
    achievementid, 
    a.title,
    a.level
FROM 
    player_achievements p
    INNER JOIN achievements a ON p.achievementid = a.id

我确实尝试更改了表格abit(将类别和级别添加到了player_achievements,感觉这是错误的,因为数据在另一个表格中)并使用了此查询:

SELECT 
    achievementid, 
    a.title 
FROM 
    player_achievements p1 
    INNER JOIN achievements a ON p1.achievementid = a.id 
WHERE 
    p1.level =(
        SELECT 
        MAX(p2.level) 
    FROM 
        player_achievements p2 
    WHERE 
        p1.category = p2.category
) 
AND playerid = 44

但它只返回了一行

2 个答案:

答案 0 :(得分:1)

请看这个:

SELECT id, title
FROM achievements JOIN (
    SELECT category, max(level) level
    FROM player_achievements JOIN achievements ON achievementid = id 
    WHERE playerid = 44
    GROUP BY category
) t USING (category, level);

答案 1 :(得分:1)

一种解决方案是将achievements添加到子查询中,如下所示

SELECT 
    achievementid, 
    title 
FROM player_achievements pa1 
INNER JOIN achievements a1 ON pa1.achievementid = a1.id 
WHERE 
    a1.level =(
        SELECT MAX(a2.level) 
        FROM player_achievements pa2 
        INNER JOIN achievements a2 ON pa2.achievementid = a2.id 
        WHERE a1.category = a2.category and 
              pa2.playerid = pa1.playerid
    ) 
AND pa1.playerid = 44

demo