使用INNER Join

时间:2018-10-16 14:53:29

标签: mysql join group-by inner-join

很抱歉,如果标题令人困惑,我有一个表,用于存储玩家以及他们在几秒钟内完成地图所花费的时间,我试图编写一个查询,以选择特定玩家拥有最快/最短的时间

我尝试了以下查询:

SELECT * 
  FROM ck_playertimes a 
  JOIN 
     ( SELECT MIN(runtimepro) runtimepro 
         FROM ck_playertimes 
        WHERE style = 0 
        group 
           by mapname
     ) b 
    ON a.runtimepro = b.runtimepro 
 WHERE steamid = 'STEAM_1:0:20019070' 
   AND style = '0'

但是它选择的时间不是特定地图的最短/最快时间,并且当表中不存在该重复项时,甚至会有一个重复项

有帮助吗? =)

2 个答案:

答案 0 :(得分:1)

您要加入的子查询应该找到每个玩家的最短运行时间 。因此,以下方法应该起作用:

SELECT c1.*
FROM ck_playertimes c1
INNER JOIN
(
    SELECT mapname, MIN(runtimepro) AS min_runtimepro
    FROM ck_playertimes
    GROUP BY mapname
) c2
    ON c1.mapname = c2.mapname AND c1.runtimepro = c2.min_runtimepro
WHERE
    c1.steamid = 'STEAM_1:0:20019070' AND
    c1.style = '0';

如果您使用的是MySQL 8+或更高版本,则写上述查询的另一种更现代的方式是使用ROW_NUMBER

SELECT *       -- but always better to list out explicit columns
FROM
(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY mapname ORDER BY runtimepro) rn
    FROM ck_playertimes
) t
WHERE rn = 1;

答案 1 :(得分:0)

您要问的是每位玩家和每张地图的最小和最大时间 这是带有分组依据的基本选择,需要bo join

我假设您从中选择的表除了以秒为单位的时间外,还包含一个player_id 并保留您提供的WHERE条件

希望有帮助

SELECT  player_id, mapname, MIN(runtimepro) As shortest, 
MAX(runtimepro) As longest
FROM ck_playertimes times

WHERE

steamid = 'STEAM_1:0:20019070'
AND style = '0'
GROUP BY 
player_id, mapname