1.查询A表与B表的关系时,如果条件中使用了exists和not exists,那么在A表和B表关联字段字段名一样的情况下,一定要使用表别名,或者在写关联条件时直接带上表名。
例如:
select * from a where not exists (select 1 from b where id = b.id )
这样写exists就没有意义,查不出数据。
一定要写成这样:
select * from a where not exists (select 1 from b where a.id = b.id )。
2.使用in和not in时A表的字段带不带表名,都一样。
select * from a where id in (select b.id from b)
select * from a where a.id in (select b.id from b)
两个查询是一样的,不过在使用阶段,最好还是带出表名,这样肯定没问题。
总结:in是查询是否包括,而exists是判断是否存在。
3.注意:exists和not exists 两个的集合等于全表,in、not in再加上空值等于全表。所以一定要根据自己的需求使用对应的条件。
select * from a where not exists (select 1 from b where a.id = b.id )
select * from a where exists (select 1 from b where a.id = b.id )
上面两个查询的集合是A表。
select * from a where a.id in (select b.id from b)
select * from a where a.id not in (select b.id from b)
select * from a where a.id is null .
上面三个查询的集合是A表。
4.关联条件用了两个字段的情况。
select * from a where (a.id,a.name) not in (select b.id , b.name from b)
如果这样查的话,一般B表两个字段都是要有值的,A表两个字段都为空的数据就会被筛掉,只要A表其中一个字段不为空,且满足条件,都会被查询出来。