MySQL“;分组方式;来自两个连接的查询

MySQL“;分组方式;来自两个连接的查询,mysql,sql,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.tea

我已生成下面的查询,该查询返回以下结果:

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)
但是,我只希望为每个用户名和活动返回一行,而不是将“赢”和“目标”列相加。在上述实例中,我希望查询返回以下内容:

+------------+------------+-----+-------+
| 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)
我相信这将涉及到该小组?或者我必须创建一个新的查询并将其与此查询相结合。正如你所看到的,我不确定下一步该怎么做。如果有人认为这将有助于获得表格的详细信息,那么请告诉我

非常感谢

我相信这将涉及到该小组

是的,会的。要获得所需的结果,不必编写单独的查询。试试下面的

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
,其中包含子查询的数据并获取所需数据。

非常感谢您的快速响应。简单而天才。我很快就会接受这个答案,因为现在接受它显然还为时过早。这个groupby不会在较新的MySQL版本上执行。(除非在兼容模式下。)常规GROUP BY规则说明:如果指定了GROUP BY子句,则SELECT列表中的每个列引用必须标识分组列或是set函数的参数!