2016-09-26 63 views
1

我公司生产的下方返回以下结果查询:MySQL的“GROUP BY”从两个连接的查询

mysql> select u.username, s.campaignno, if(f.hometeamscore>f.awayteamscore,1,0) as Win, f.hometeamscore as Goals from straightred_fixture f, straightred_userselection s, auth_user u where s.fixtureid = f.fixtureid and s.teamselectionid = f.hometeamid and s.user_id = u.id union all 
    -> select u.username, s.campaignno, if(f.awayteamscore>f.hometeamscore,1,0) as Win, f.awayteamscore as Goals from straightred_fixture f, straightred_userselection s, auth_user u where s.fixtureid = f.fixtureid and s.teamselectionid = f.awayteamid and s.user_id = u.id; 
+------------+------------+-----+-------+ 
| username | campaignno | Win | Goals | 
+------------+------------+-----+-------+ 
| tingeyal | 34910256 | 1 |  5 | 
| shanu  | 35410256 | 1 |  4 | 
| tingeyal | 34910256 | 0 |  0 | 
| kOS  | 35210256 | 1 |  2 | 
| kOS  | 35210256 | 0 |  0 | 
| shanu  | 35410256 | 1 |  3 | 
| kriste8403 | 35510256 | 1 |  3 | 
| kriste8403 | 35510256 | 0 |  0 | 
+------------+------------+-----+-------+ 
8 rows in set (0.00 sec) 

不过,我想只返回一行对每个用户名& campaignno组合相加无论是“赢“和”目标“栏。在上面的例子中,我想查询返回以下内容:

+------------+------------+-----+-------+ 
| username | campaignno | Win | Goals | 
+------------+------------+-----+-------+ 
| tingeyal | 34910256 | 1 |  5 | 
| shanu  | 35410256 | 2 |  7 | 
| kOS  | 35210256 | 1 |  2 | 
| kriste8403 | 35510256 | 1 |  3 | 
+------------+------------+-----+-------+ 
4 rows in set (0.01 sec) 

我相信这会涉及到群组?或者,也许我必须创建一个新的查询并将其与此结合。正如你所看到的,我不确定我的下一步应该是什么。如果有人认为这将是有帮助的有表格的细节,然后让我知道。

非常感谢。

回答

1

我相信这会涉及到群组?

是的,它会的。为了获得理想的结果,您不必编写单独的查询。尝试下面。

SELECT tablea.username, tablea.campaignno, SUM(tablea.Win) Win, SUM(tablea.Goals) Goals 
FROM 
(select u.username, s.campaignno, if(f.hometeamscore>f.awayteamscore,1,0) as Win, f.hometeamscore as Goals from straightred_fixture f, straightred_userselection s, auth_user u where s.fixtureid = f.fixtureid and s.teamselectionid = f.hometeamid and s.user_id = u.id 
union all 
select u.username, s.campaignno, if(f.awayteamscore>f.hometeamscore,1,0) as Win, f.awayteamscore as Goals from straightred_fixture f, straightred_userselection s, auth_user u where s.fixtureid = f.fixtureid and s.teamselectionid = f.awayteamid and s.user_id = u.id) AS tablea 
WHERE 1 
GROUP BY tablea.username 

上面的语句将创建两个子查询的临时表tablea包含数据并获取所需的数据。

+1

非常感谢您的迅速回复。简单但天才。我很快就会接受这个答案,显然现在接受它还为时过早。 –

+0

GROUP BY不会在较新的MySQL版本上执行。 (除非在兼容模式下)。一般的GROUP BY规则说:如果指定了GROUP BY子句,SELECT列表中的每个列引用必须标识一个分组列或者是一个set函数的参数! – jarlh