我试过用两列分组:
SELECT recipient_id, sender_id, count(*) FROM messengers WHERE recipient_id=41 OR sender_id=41 group by recipient_id, sender_id
输出如下所示:
我如何将第1行和第2行合并为一行,因为recipient_id和sender_id具有相同的值40和41。
答案 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)