繁体   English   中英

MYSQL 将一个表中的一个列连接到另一个表中的两个 count()

[英]MYSQL join one colum from one table to two count() in another

我有一张表,用于存储在线游戏的排名。 此表(玩家)有 4 列(玩家 ID、玩家名称、当前 ELO 和玩家状态)。 我也想显示赢/输的比赛,但该信息在重播表中,每场比赛都有一行。 我可以使用 count(*) 函数轻松计算赢局或输局的数量:

select Winner, count(*) from Replays group by Winner;
select Loser, count(*) from Replays group by Loser;

但是,我找不到连接两个表的方法,所以我的最终结果是这样的:

+-------------+-------------+-----------+------------+
| Player_Name | Current_ELO | Won games | Lost games |
+-------------+-------------+-----------+------------+
| John        | 1035        | 5         | 3          |
+-------------+-------------+-----------+------------+

我最好的猜测是这样,但是返回太多结果,因为我无法为每个计数分别按赢家/输家对“计数()”进行分组:

select Player_Name,  Current_ELO, Player_Status, count(Winner_Replays.Winner), count(Loser_Replays.Loser) from Players
inner join Replays as Winner_Replays on Winner_Replays.Winner = Players.Player_Name
inner join Replays as Loser_Replays on Loser_Replays.Loser = Players.Player_Name
group by Winner_Replays.Winner order by Current_ELO desc;

理想情况下,由于某些玩家可能有 0 胜或 0 负,我希望它为这些用户返回 0(如果可能的话)。 谢谢!

您可以在播放结果的玩家列表上使用INNER JOIN使用以下内容。 您可以使用SUMCASE来获取每个玩家的获胜/失败计数。

SELECT Players.Player_Name, ANY_VALUE(Current_ELO), ANY_VALUE(Player_Status),
  SUM(CASE WHEN result = 'L' THEN 1 ELSE 0 END) AS Lost_Games, 
  SUM(CASE WHEN result = 'W' THEN 1 ELSE 0 END) AS Won_Games
FROM Players INNER JOIN (
  SELECT 'W' AS result, Winner AS Player_Name FROM Replays
  UNION ALL
  SELECT 'L', Loser FROM Replays
) win_lose ON Players.Player_Name = win_lose.Player_Name
GROUP BY Players.Player_Name
ORDER BY ANY_VALUE(Current_ELO) DESC;

您还可以像这样使用LEFT JOIN解决方案:

SELECT Players.Player_Name, ANY_VALUE(Current_ELO) AS Current_ELO, ANY_VALUE(Player_Status) AS Player_Status,
  COUNT(DISTINCT rLoser.ReplayID) AS Lost_Games, 
  COUNT(DISTINCT rWinner.ReplayID) AS Won_Games
FROM Players
  LEFT JOIN Replays AS rWinner ON rWinner.Winner = Players.Player_Name
  LEFT JOIN Replays AS rLoser ON rLoser.Loser = Players.Player_Name
GROUP BY Players.Player_Name
ORDER BY ANY_VALUE(Current_ELO) DESC;

dbfiddle.uk 上的演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM