mysql - 如何加入两个计数的总和?

时间:2012-11-23 14:43:30

标签: mysql join count

我目前有一张匹配结果表

+----------+----------+--------+-----------+--------+-----------+-----------+-----------+
| hometeam | awayteam | p1home | p2home... | p1away | p2away... | homescore | awayscore |
+----------+----------+--------+-----------+--------+-----------+-----------+-----------+

我用相当笨重的

查询
SELECT
(SELECT COUNT(hometeam)
FROM fixture_data
WHERE (p1home = '$playerID' OR p2home = '$playerID' OR...)
AND hometeam = '$teamname')
+
(SELECT COUNT(awayteam)
FROM fixture_data
WHERE (p1home = '$playerID' OR p2home = '$playerID' OR...)
AND awayteam= '$teamname')
AS matches_played

获取特定玩家$ playerID为特定团队$ teamname

播放的特定玩家的匹配数量

桌面玩家很简单

+----------+-----------+-----------+
| playerID | firstname | surname   |
+----------+-----------+-----------+

在致电后的那一刻

SELECT * FROM players

我通过PHP为每个玩家调用初始查询,因为我正努力将两个查询一起加入一个单一的MYSQL查询以产生一个表

+----------+-----------+-----------+----------------+
| playerID | firstname | surname   | matches_played |
+----------+-----------+-----------+----------------+

这可能吗?或者,我目前使用PHP的解决方案是否会像它将要获得的效率一样高效?

3 个答案:

答案 0 :(得分:2)

我建议将这些查询合并为:

SELECT COUNT(*) AS matches_played
FROM fixture_data
WHERE (p1home = '$playerID' OR p2home = '$playerID' OR...)
AND ( awayteam= '$teamname' OR hometeam = '$teamname')

答案 1 :(得分:2)

如果你将玩家列表从匹配表中取出并将其放入一个单独的玩家,团队,匹配表中,你可以让自己更容易。那么你的总和将是加入三和计数比赛的问题。如果玩家在家或离开,或者甚至有多少人玩某场比赛都没关系。

答案 2 :(得分:1)

这应该有效:

SELECT p.playerID, p.firstname, p.surname, COUNT(*)
  FROM players p, fisture_data f
 WHERE p.playerID='$playerID'
    AND (((p.playerID = f.p1home OR p.playerID=f.p2home...) AND f.hometeam='$teamname')
        OR ((p.playerID = f.p1away OR p.playerID=f.p2away...) AND f.awayteam='$teamname'))
GROUP BY p.playerID, p.firstname, p.surname

但是模型不是最优的,你应该创建一个新的表来存储链接播放器/匹配/团队。