选择加入MySQL和PHP的过滤总和

时间:2014-08-02 08:55:42

标签: php mysql join sum

我正在开发一个投注系统,基本上有一组比赛(或游戏)。比赛总是有两支球队,用户可以在这两支球队下注。

我有以下数据库结构:

匹配

Table "matches"

小组:

Table "teams"

赌注:

Table "bets"

我想用我的查询做的是从数据库中获取每场比赛中与每支球队相关的比赛和投注金额总和,并列出所有比赛以及与之相关的所有信息。

我远:

$query="SELECT 
a.*, 
SUM(b.amount) AS sumA, 
SUM(c.amount) AS sumB, 
d.name AS teamNameA, 
e.name AS teamNameB 
FROM matches AS a 
LEFT JOIN bets AS b ON(a.teamA = b.team_id AND a.id = b.match_id)
LEFT JOIN bets AS c ON(a.teamB = c.team_id AND a.id = c.match_id)
LEFT JOIN teams AS d ON(a.teamA = d.id)
LEFT JOIN teams AS e ON(a.teamB = e.id) GROUP BY id"

$result = mysql_query($query);

$resultArray = array();
while($row = mysql_fetch_assoc($result)){
    $resultArray[] = $row;
}

print_r($resultArray);
exit();

打印什么:

Array
(
    [0] => Array
        (
            [id] => 1
            [teamA] => 1
            [teamB] => 2
            [teamNameA] => "Team 1"
            [teamNameB] => "Team 2"
            [sumA] => 400
            [sumB] => 200
        )
    [1] => Array
        (
            [id] => 1
            [teamA] => 1
            [teamB] => 2
            [teamNameA] => "Team 1"
            [teamNameB] => "Team 2"
            [sumA] => 
            [sumB] => 
        )
    [2] => Array
        (
            [id] => 1
            [teamA] => 1
            [teamB] => 2
            [teamNameA] => "Team 1"
            [teamNameB] => "Team 2"
            [sumA] => 
            [sumB] => 
        )
)

这几乎是完美的,但第一行的“sumA”和“sumB”的数量是错误的。 “sumA”应该等于200,“sumB”应该等于100.当然它是重复总和过程。我尝试在SUM中使用“DISTINCT”语句,但是它们消除了金额相等的值,“sumA”为100,“sumB”为50,还有错误。

3 个答案:

答案 0 :(得分:1)

我为您创建了一个解决方案,其中包括总和(金额),团队ID和团队名称。

SELECT SUM(amount), bets.id, teams.name from bets
INNER JOIN teams ON bets.team_id = teams.id GROUP BY teams.id;

它与PHP打印的不一样,但我发现它更有用。

你不妨看看我写的这个SQLFiddle。

祝你好运。

http://sqlfiddle.com/#!2/7ffc6/17

答案 1 :(得分:1)

试试这个sql

SELECT  A.id as match_id, A.teamA as teamA, A.teamB as teamB, 
        (SELECT B.name FROM teams B WHERE B.id=A.teamA LIMIT 1) AS teamNameA, 
        (SELECT C.name FROM teams C WHERE C.id=A.teamB LIMIT 1) AS teamNameB, 
        (SELECT sum(D.amount) FROM bets D WHERE D.match_id=A.id AND D.team_id=A.teamA) as sumA , 
        (SELECT sum(E.amount) FROM bets E WHERE E.match_id=A.id AND E.team_id=A.teamB) as sumB 
FROM `matches` A

这太冗长了并且有时间执行但是你会根据你的选择获得输出

答案 2 :(得分:0)

使用@SKRocks的提示,我终于找到了正确的解决方案,用bets表的LEFT JOIN代替子查询,如下所示:

$query="SELECT 
a.*, 
(SELECT sum(D.ammount) FROM bets AS D WHERE D.match_id=a.id AND D.team_id=a.teamA) AS sumA, 
(SELECT sum(E.ammount) FROM bets AS E WHERE E.match_id=a.id AND E.team_id=a.teamB) AS sumB, 
d.name AS teamNameA, 
e.name AS teamNameB 
FROM matches AS a 
LEFT JOIN teams AS d ON(a.teamA = d.id)
LEFT JOIN teams AS e ON(a.teamB = e.id) GROUP BY id";

现在我得到了正确的结果并保持了LEFT JOINS的性能。我选择这个答案作为最终解决方案,因为它是我实际使用的。但是你给了我正确的提示来构建这个解决方案。