请教mysql取交集的问题现有 dept表id deptid
1 20
2 20
3 20user表id userid
1 33
2 34
3 34dept表的id 和user表的id关联
现需要取出deptid=20 并且 userid 一样的值 如上表,取出的值应为空,如果把user表id=1 的值改为34 则应该取出34
如何写出这个sql语句
1 20
2 20
3 20user表id userid
1 33
2 34
3 34dept表的id 和user表的id关联
现需要取出deptid=20 并且 userid 一样的值 如上表,取出的值应为空,如果把user表id=1 的值改为34 则应该取出34
如何写出这个sql语句
建议你列出你的表结构,并提供测试数据以及基于这些测试数据的所对应正确结果。
问题说明越详细,回答也会越准确!参见如何提问。(提问的智慧)当您的问题得到解答后请及时结贴.
http://topic.csdn.net/u/20090501/15/7548d251-aec2-4975-a9bf-ca09a5551ba5.html
上面的的数据应该是返回空
如果把user表id=1 的值改为34 应该返回34
from user u
where id in (select id from dept)
and not exists (select 1 from user where id in (select id from dept) and userid<>u.userid)
from user u
where id in (select id from dept where deptid=20)
and not exists (select 1 from user where id in (select id from dept deptid=20) and userid<>u.userid)忘了加上 where deptid=20 了
from user u inner join dept d on u.id=d.id
where d.deptid=20
and not exists (select 1 from user inner join dept on user.id=dept.id where userid<>u.userid)改成JOIN效率会高一些。
结果应该为34 但是运行了你的sql语句为空,请老兄赐教
id userid
1 34
2 34
3 34
1 30