虽然 SQLite 有group_concat()
,但它在这里无济于事,因为连接元素的顺序是任意的。这是最简单的方法。
相反,我们必须以相关的方式考虑这一点。想法是执行以下操作:
- 计算两个 id 共有的颜色数量
- 计算每个id上的颜色数
- 选择这三个值相等的 id 对
- 通过对中的最小 id 识别每一对
然后最小值的不同值是您想要的列表。
以下查询采用这种方法:
select distinct MIN(id2)
from (select t1.id as id1, t2.id as id2, count(*) as cnt
from t t1 join
t t2
on t1.color = t2.color
group by t1.id, t2.id
) t1t2 join
(select t.id, COUNT(*) as cnt
from t
group by t.id
) t1sum
on t1t2.id1 = t1sum.id and t1sum.cnt = t1t2.cnt join
(select t.id, COUNT(*) as cnt
from t
group by t.id
) t2sum
on t1t2.id2 = t2sum.id and t2sum.cnt = t1t2.cnt
group by t1t2.id1, t1t2.cnt, t1sum.cnt, t2sum.cnt
我实际上是在 SQL Server 中通过将此with
子句放在前面来测试的:
with t as (
select 1 as id, 'r' as color union all
select 1, 'g' union all
select 1, 'b' union all
select 2 as id, 'r' as color union all
select 2, 'g' union all
select 2, 'b' union all
select 3, 'r' union all
select 4, 'y' union all
select 4, 'p' union all
select 5 as id, 'r' as color union all
select 5, 'g' union all
select 5, 'b' union all
select 5, 'p'
)