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)
我相信這會涉及到羣組?或者,也許我必須創建一個新的查詢並將其與此結合。正如你所看到的,我不確定我的下一步應該是什麼。如果有人認爲這將是有幫助的有表格的細節,然後讓我知道。
非常感謝。
非常感謝您的迅速回復。簡單但天才。我很快就會接受這個答案,顯然現在接受它還爲時過早。 –
GROUP BY不會在較新的MySQL版本上執行。 (除非在兼容模式下)。一般的GROUP BY規則說:如果指定了GROUP BY子句,SELECT列表中的每個列引用必須標識一個分組列或者是一個set函數的參數! – jarlh