"Symmetric" 多列 GROUP BY

"Symmetric" GROUP BY on multiple columns

我有一个 table 这样的:

_id sender_id receiver_id text
1   1         2           xxx
2   2         1           yyy
3   1         2           xyz
4   3         1           abc

我需要对 sender_idreceiver_id 列进行 GROUP BY,但它应该是对称的,因此 {1,2} 和 {2,1} 应该被视为同一组。

此查询可以在随机 DBMS 上执行,因此它应该尽可能标准。

我认为你需要 two CASE 表达式,因为你在两列上分组:

GROUP BY CASE WHEN sender_id < receiver_id THEN sender_id
              ELSE receiver_id
         END,
         CASE WHEN sender_id < receiver_id THEN receiver_id
              ELSE sender_id
         END,

如果您正在使用 MySQL,则考虑使用 LEAST()GREATEST() 技巧:

SELECT LEAST(sender_id, receiver_id), GREATEST(sender_id, receiver_id)
FROM yourTable
GROUP BY LEAST(sender_id, receiver_id), GREATEST(sender_id, receiver_id)

在 SQLite 中你可以使用 MAX()MIN() 作为 scalar functions:

SELECT MIN(sender_id, receiver_id), MAX(sender_id, receiver_id)
FROM yourTable
GROUP BY MIN(sender_id, receiver_id), MAX(sender_id, receiver_id)