MySQL“Group By”来自两个加入的查询

时间:2016-09-26 06:58:23

标签: mysql sql

我在下面生成了查询,返回以下结果:

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 个答案:

答案 0 :(得分: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,其中包含两个子查询的数据并获取所需的数据。