来自两个连接查询的 MySQL "Group By"

标签 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)

但是,我希望只为每个用户名和广告系列返回一行,而不是汇总“赢得”和“目标”列的组合。在上述实例中,我希望查询返回以下内容:

+------------+------------+-----+-------+
| 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)

我相信这会涉及 group by?或者,也许我必须创建一个新查询并将其与这个查询结合起来。如您所见,我不确定下一步应该做什么。如果有人认为提供表格详细信息会有所帮助,请告诉我。

非常感谢。

最佳答案

I believe this will involve the group by?

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

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

关于来自两个连接查询的 MySQL "Group By",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39696509/

相关文章:

mysql - 是否有任何函数可以在类似 sql 中查找具有特殊字符的结果?

sql - 在自定义 SSIS 任务中执行 SQL 的首选方式是什么?

php - 重复的结果

c# - 通过查询获取表主键列

mysql - bash 从 bash 命令更新 mysql

php - 如何按每个主题显示我的数据库文件

java - 为什么我的 JPanel 不显示?

mysql - 如何从函数内部的查询获取结果

mysql分隔符问题

sql - PostgreSQL 应该在一条语句中同时返回计数和行数