我有一个基本的表结果(id,winner_id,loser_id)。 winner_id和loser_id都引用“玩家”表中的相同列。我可以通过1个GROUP BY查询来检索总赢数,并且可以检索非常类似的一个来检索总损失数。
select winner_id, count(*) as total_wins
from results group by winner_id order by total_wins desc
select loser_id, count(*) as total_losses
from results group by loser_id order by total_losses desc
现在我正在尝试执行一个基本上将这两个查询组合在一起并返回按ID分组的total_results的查询。有人能指出我正确的方向吗?
答案 0 :(得分:2)
如果您确实返回了播放器的ID,那么查询似乎更有意义。否则,您只需订购一定数量的数字,但不能参考他们对应的数字:
select player_id, sum(total) total from (
select winner_id player_id, count(*) total from results group by winner_id
union all
select loser_id, count(*) from results group by loser_id
) s
group by player_id
order by total desc
答案 1 :(得分:1)
您可以在每个子查询的结果中包含id并将它们连接在一起。然后你可以减去两个计数:
SELECT id, total_wins - total_losses AS total_results
FROM (
SELECT winner_id AS id, count(*) AS total_wins
FROM results
GROUP BY winner_id
) AS w
JOIN (
SELECT loser_id AS id, count(*) AS total_losses
FROM results
GROUP BY loser_id
) AS l USING (id)
ORDER BY total_results DESC;
请注意,[INNER] JOIN
会从两个子查询中未显示的结果中删除任何id
。
您可以使用 OUTER JOIN
来保留此类行,并且必须添加COALESCE
来处理NULL
值:
SELECT id, COALESCE(total_wins, 0) - COALESCE(total_losses, 0) AS total_results
FROM (
SELECT winner_id AS id, count(*) AS total_wins
FROM results
GROUP BY winner_id
) AS w
FULL OUTER JOIN (
SELECT loser_id AS id, count(*) AS total_losses
FROM results
GROUP BY loser_id
) AS l USING (id)
ORDER BY total_results DESC;
击> <击> 撞击>
我刚刚意识到MySQL doesn't support FULL OUTER JOIN
使用@Mosty supplied的UNION ALL
方法
或者使用LEFT JOIN
将两个子查询连接到包含所有ID的表。