GROUP BY(a,b)和(b,a)

时间:2016-07-22 16:05:27

标签: php mysql sql group-by

我有一张这样的表:

player1    player2    player3    player4    score1    score2
   1          2          3          4         11         2  
   1          2          3          4          4         11
   2          1          3          4         11         5

如果我查询:SELECT player1, player2, SUM(score1) FROM mytable GROUP BY player1, player2

我会得到:

player1   player2   SUM(score1)
   1         2          15
   2         1          11

但是,我希望GROUP BY player1,player2 AND player2,player1同时获得:

player   player   SUM(score1)
   1         2         26

有没有人知道它是否可能(我使用MySQL)。

如果不是,您是否知道在PHP中使用它的好方法?

2 个答案:

答案 0 :(得分:0)

您可以使用least()greatest()

select least(player1, player2), greatest(player1, player2), sum(score1)
from mytable
group by least(player1, player2), greatest(player1, player2);

答案 1 :(得分:-1)

或试试这个

select min(player1) as player1,max(player2) as player2, sum(score1) as score1 from
(
select player1, player2, SUM(score1) as score1 FROM mytable GROUP BY player1, player2
) as t