汇总不同的查询

时间:2019-03-05 13:22:28

标签: php mysql sql phpmyadmin inner-join

大家下午好

对于我实习的项目,我正在为休息时间玩的游戏制作仪表板。我们玩飞镖,国际足联和台球。

例如:

SELECT pw.name AS `winner`
     , COUNT(*) AS total 
  FROM billiard_games g 
  JOIN players p1 
    ON p1.id = g.player_1 
  JOIN players p2 
    ON p2.id = g.player_2 
  LEFT 
  JOIN billiard_winners w 
    ON w.id = g.id 
  LEFT 
  JOIN players pw 
    ON pw.id = w.winner 
 GROUP 
    BY winner

这比以下结果要好:

Winner | Total
---------------
Name1 | 5
Name2 | 7

这意味着name1赢得5次,name2赢得7次。到目前为止一切顺利吗?

我对其他游戏有不同的查询。在上面的查询中,我要求Billiard_games。其他查询是相同的,但我不是dilli_games,而是问dart_games和fifa_game。

在应用程序的首页上,我希望获得一个概述。与所有时间的赢家。该表需要计算一个玩家的所有胜利。因此,FIFA,Billiard&Darts的胜利全都胜过了。

我尝试过:

SELECT
(SELECT pw.name AS `winner`, COUNT(*) AS total FROM billiard_games g INNER JOIN players p1 ON p1.id = g.player_1 INNER JOIN players p2 ON p2.id = g.player_2 LEFT JOIN billiard_winners w ON w.id = g.id LEFT JOIN players pw ON pw.id = w.winner GROUP BY winner)+
(SELECT pw.name AS `winner`, COUNT(*) AS total FROM dart_games g INNER JOIN players p1 ON p1.id = g.player_1 INNER JOIN players p2 ON p2.id = g.player_2 LEFT JOIN dart_winners w ON w.id = g.id LEFT JOIN players pw ON pw.id = w.winner GROUP BY winner)+
(SELECT pw.name AS `winner`, COUNT(*) AS total FROM fifa_games g INNER JOIN players p1 ON p1.id = g.player_1 INNER JOIN players p2 ON p2.id = g.player_2 LEFT JOIN fifa_winners w ON w.id = g.id LEFT JOIN players pw ON pw.id = w.winner GROUP BY winner)
AS SumCount

但是这不起作用。谁能帮我?我希望所有名称和所有胜利都在一个视图中。

3 个答案:

答案 0 :(得分:0)

请尝试这个。

SELECT pw.name AS 'winner', COUNT(pw.name) AS total 
FROM billiard_games g 
INNER JOIN players p1 
ON p1.id = g.player_1 
INNER JOIN players p2 
ON p2.id = g.player_2 
LEFT JOIN billiard_winners w 
ON w.id = g.id 
LEFT JOIN players pw ON pw.id = w.winner GROUP BY winner

答案 1 :(得分:0)

您可以尝试使用UNION ALL

select winner, sum(total)
from
(
SELECT pw.name AS `winner`, COUNT(*) AS total 
FROM billiard_games g INNER JOIN players p1 ON p1.id = g.player_1 INNER JOIN players p2 ON p2.id = g.player_2 LEFT JOIN billiard_winners w ON w.id = g.id LEFT JOIN players pw ON pw.id = w.winner GROUP BY winner
union all
SELECT pw.name AS `winner`, COUNT(*) AS total FROM dart_games g INNER JOIN players p1 ON p1.id = g.player_1 INNER JOIN players p2 ON p2.id = g.player_2 LEFT JOIN dart_winners w ON w.id = g.id LEFT JOIN players pw ON pw.id = w.winner 
GROUP BY winner
union all
SELECT pw.name AS `winner`, COUNT(*) AS total FROM fifa_games g INNER JOIN players p1 ON p1.id = g.player_1 INNER JOIN players p2 ON p2.id = g.player_2 LEFT JOIN fifa_winners w ON w.id = g.id LEFT JOIN players pw ON pw.id = w.winner 
GROUP BY winner
) A group by winner

答案 2 :(得分:0)

尽管相当复杂,但为了运行查询,请删除+并尝试像union那样使用Select * from (<your_query_with_+changed_to_union>)来至少运行它。