简体   繁体   English

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

[英]mysql - how do I join a sum of two counts?

I currently have a table of match results 我目前有一个匹配结果表

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

which I query with the rather clunky 我用相当笨重的东西查询

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

to get the number of matches a particular player $playerID has played for a particular team $teamname 获得特定玩家$ playerID为特定团队$ teamname所玩的匹配数量

The table players is a simple 桌上玩家很简单

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

At the moment after calling 在打电话后的那一刻

SELECT * FROM players

I call the initial query via PHP for each player as I'm struggling to join the two queries together into one single MYSQL query to result in a table 我通过PHP为每个玩家调用初始查询,因为我正在努力将两个查询连接成一个单一的MYSQL查询以产生一个表

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

Is this possible? 这可能吗? Or is my current solution using PHP going to be as efficient as it's going to get? 或者,我目前使用PHP的解决方案是否会像它将获得的效率一样高效?

I'd suggest combining those queries into one like: 我建议将这些查询合并为:

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

You could make this easier on yourself if you take the player list out of the match table and put it into a separate table of player, team, match. 如果你将玩家列表从匹配表中取出并将其放入一个单独的玩家,团队,匹配表中,你可以让自己更容易。 Then your sum would be a matter of joining the three and counting matches. 那么你的总和将是加入三和计数比赛的问题。 It wouldn't matter if the player was home or away or even how many ppl played a given match. 无论玩家是在家还是在外,或者甚至有多少人参加了比赛。

This should work : 这应该工作:

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

But the model is not optimal, you should create a new table where you store the link player/match/team. 但是模型不是最优的,你应该创建一个新的表来存储链接播放器/匹配/团队。

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

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