按两列分组,反之亦然

时间:2016-04-18 16:51:23

标签: mysql sql database

我试过用两列分组:

SELECT recipient_id, sender_id, count(*) FROM messengers WHERE recipient_id=41 OR sender_id=41 group by recipient_id, sender_id 

输出如下所示:

enter image description here

我如何将第1行和第2行合并为一行,因为recipient_id和sender_id具有相同的值40和41。

1 个答案:

答案 0 :(得分:3)

您可以使用的一个技巧是GROUP BY两个ID列的较小和两个ID列的更大

SELECT LEAST(recipient_id, sender_id), GREATEST(recipient_id, sender_id), COUNT(*)
FROM messengers
WHERE recipient_id = 41 OR sender_id = 41
GROUP BY LEAST(recipient_id, sender_id), GREATEST(recipient_id, sender_id)