有table1(id,role)有数据:
id role
1 210
1 211
2 210
2 214
3 210
3 211
3 212
3 214
4 210
4 214现在想查出这样的id,其对应的role集合中包含有id=2对应的role。
id=2的role集合包括(210,214)
id=3的role集合包括(210,211,212,214)
id=1的role集合包括(210,211)
id=4的role集合包括(210,214)
那么就应该查出的id是3,4
id role
1 210
1 211
2 210
2 214
3 210
3 211
3 212
3 214
4 210
4 214现在想查出这样的id,其对应的role集合中包含有id=2对应的role。
id=2的role集合包括(210,214)
id=3的role集合包括(210,211,212,214)
id=1的role集合包括(210,211)
id=4的role集合包括(210,214)
那么就应该查出的id是3,4
where not exists
(select 1 from table1 t2
where t2.id = 2
and t2.role not in (select role from table1 t3 where t3.id = t1.id)
);上面那个可能不行
WHERE NOT EXISTS
(SELECT 1
FROM table1 t2
WHERE t2.id=2 AND role NOT IN
(SELECT role
FROM table1 t3
WHERE t3.id=t1.id))
AND id <> 2;
也谢谢3楼zcs_1.