为什么 select * from user where id in(select uid form zzjg where tag=0)查不出数据
而用select * from user where exists (select uid form zzjg where tag=0) 就可以
首先确定数据肯定是有的, 还有in和exists到底有什么区别?我认为是一样的,只是exists效率会快一些
而用select * from user where exists (select uid form zzjg where tag=0) 就可以
首先确定数据肯定是有的, 还有in和exists到底有什么区别?我认为是一样的,只是exists效率会快一些
select * from user where id in(select uid form zzjg where tag=0)
只要必须要id在uid里面才可以
select * from user where exists (select uid form zzjg where tag=0)
只要select uid form zzjg where tag=0查出任何记录,则user表所有记录都符合条件
where u.id=z.uid and z.tag=0;看看有没有结果。2语句不等价。若要等价,下面这个应该为:
select * from user u where exists (select 1 form zzjg z where u.id=z.uid and z.tag=0)
select * from user a where exists
(select 1 form zzjg b where tag=0 and b.uid=a.id)
你2句sql的逻辑不一样啊,第一句是user表跟zzjg表有了id字段、uid字段来关联,而第二局是没有关联的。你吧第二句改成以下
select a.* from user a where exists
(select 1 form zzjg b where b.tag=0 and b.uid=a.id);
那么这样2个sql语句执行的结果就是一样的了!另外in或者exists结果上一样,只是在不同的情况下,效率不一样而已。
(1)当只显示一个表的数据如A,关系条件只一个如ID时,使用IN更快:
select * from A where id in (select id from B)
(2)当只显示一个表的数据如A,关系条件不只一个如ID,col1时,使用IN就不方便了,可以使用EXISTS:
select * from A
where exists (select 1 from B where id = A.id and col1 = A.col1)
(3)当只显示两个表的数据时,使用IN,EXISTS都不合适,要使用连接:
select * from A left join B on id = A.id
对于这一句:select * from user where id in(select uid form zzjg where tag=0)
如果括号中的查询结果有一行是 null, 则查询数据为空,但是若将 in 换为 exist 则不会,他会显示出 not null 的符合条件的。也就是说,当没有空记录时, in 和 exist 基本相同,但若有 null ,则不同。
(1)当只显示一个表的数据如A,关系条件只一个如ID时,使用IN更快:
select * from A where id in (select id from B)
(2)当只显示一个表的数据如A,关系条件不只一个如ID,col1时,使用IN就不方便了,可以使用EXISTS:
select * from A
where exists (select 1 from B where id = A.id and col1 = A.col1)
(3)当只显示两个表的数据时,使用IN,EXISTS都不合适,要使用连接:
select * from A left join B on id = A.id
而 exists 一般都会与外部有关联, 所以每处理一行都会 再搜索一次(表的所有行的具体列或表的某列的索引,得到一条时返回不再继续搜索,转而处理下一行), 效率依赖于匹配度
select * from user where id in(select uid form zzjg where tag=0)
--虽然select uid from zzjg where tag=0返回有数据,但id不在返回的数据中,所以最终还是没记录
select * from user where exists (select uid form zzjg where tag=0)
--只要select uid from zzjg where tag=0返回有数据,exists就是true,就是显示select * from user的记录