有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

解决方案 »

  1.   

    select distinct t.id from table1 t where not exists (select 1 from table1 t2 where t2.id = 2 and t2.role != t1.role );试试这个可以吗
      

  2.   

    select distinct t.id from table1 t 
    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) 
         );上面那个可能不行
      

  3.   

    同意二楼,但是有点小问题,改造下:SELECT DISTINCT id FROM table1 t1
      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;
      

  4.   

    谢谢2楼shiyiwan,稍作修改就对了。
    也谢谢3楼zcs_1.