我有以下mysql表:
id | member |
1 | abc
1 | pqr
2 | xyz
3 | pqr
3 | abc
我一直在尝试编写一个查询,该查询将返回与给定id具有完全相同成员的id。例如,如果给定的id为1,则查询应返回3,因为id 1和id 3都具有完全相同的成员viz。 {abc,pqr}。有什么指针吗?欣赏它。
编辑:该表可能有重复项,例如id 3可能有成员{abc,abc}而不是{pqr,abc},在这种情况下,查询不应返回id 3。
答案 0 :(得分:1)
这是一个找到整个表的匹配对的解决方案 - 您可以根据需要添加where子句进行过滤。基本上它基于相等的“成员”和不等“id”进行自我加入。然后,它比较由2个ID分组的结果计数,并将它们与原始表中的那些ID的总计数进行比较。如果它们都匹配,则意味着它们具有相同的成员。
select
t1.id, t2.id
from
table t1
inner join table t2
on t1.member = t2.member
and t1.id < t2.id
inner join (select id, count(1) as cnt from table group by id) c1
on t1.id = c1.id
inner join (select id, count(1) as cnt from table group by id) c2
on t2.id = c2.id
group by
t1.id, t2.id, c1.cnt, c2.cnt
having
count(1) = c1.cnt
and count(1) = c2.cnt
order by
t1.id, t2.id
这是我使用的一些样本数据,它返回了(1,3)和(6,7)
的匹配项insert into table
values
(1, 'abc'), (1, 'pqr'), (2, 'xyz'), (3, 'pqr'), (3, 'abc'), (4, 'abc'), (5, 'pqr'),
(6, 'abc'), (6, 'def'), (6, 'ghi'), (7, 'abc'), (7, 'def'), (7, 'ghi')
答案 1 :(得分:0)
试试这个:
declare @id int
set @id=1
select a.id from
(select id,COUNT(*) cnt from sample_table
where member in (select member from sample_table where id=@id)
and id <>@id
group by id)a
join
(select count(distinct member) cnt from sample_table where id=@id)b
on a.cnt=b.cnt
答案 2 :(得分:0)
使用子查询的类似(对Derek Kromm的方法):
SELECT id
FROM mc a
WHERE
id != 1 AND
member IN (
SELECT member FROM mc WHERE id=1)
GROUP BY id
HAVING
COUNT(*) IN (
SELECT COUNT(*) FROM mc WHERE id=1) AND
COUNT(*) IN (
SELECT COUNT(*) FROM mc where id=a.id);
这里的逻辑是我们需要符合以下两个条件的所有ID: