1.【in】
select * from tables_name where column in (select column from B);
2.【exists】
select * from tables_name where exists(select..);
3.【exists与in的关系】
二者是可以达到同一个目标的:
select * from ts_user_2 where id [not] in (select id from ts_user );
select * from ts_user_2 where [not] EXISTS (select id from ts_user where id = ts_user_2.id )
如果查询的两个表大小相当,那么用in和exists差别不大。
如果两个表中一个较小,一个是大表,则子查询表大的用exists,子查询表小的用in:
例如:表A(小表),表B(大表)
① 子查询表为表B:
select * from A
where cc in (select cc from B)
//效率低,用到了A表上cc列的索引;
select * from A
where exists(select cc from B where cc=A.cc)
//效率高,用到了B表上cc列的索引。
② 子查询表为表A:
select * from B
where cc in (select cc from A)
//效率高,用到了B表上cc列的索引;
select * from B
where exists(select cc from A where cc=B.cc)
//效率低,用到了A表上cc列的索引。
not in 和not exists如果查询语句使用了not in 那么内外表都进行全表扫描,没有用到索引;而not extsts 的子查询依然能用到表上的索引。
所以无论哪个表大,用not exists都比not in要快。