← 返回首页
MySQL基础教程(十六)
发表时间:2020-03-18 01:54:10
讲解MySQL的exists与in的区别

1.exists

当 exists里的条件语句能够返回记录行时(无论记录行是多少,只要能返回),条件就为真 , 返回当前loop到的这条记录。反之如果exists里的条件语句不能返回记录行,条件为假,则当前loop到的这条记录被丢弃。

exists的条件就像一个boolean条件,当能返回结果集则为1,不能返回结果集则为 0。

语法格式如下:

select * from tables_name where [not] exists(select..);

实例: 有学生表和用户表数据如下。

例如:如果students表中有sid为4的记录,那么将返回所有users表中的记录;否则,返回记录为空。 测试代码:

select * from users where  EXISTS (select * from students where sid=4)

2.in

语法格式如下:

select * from A where column in (select column from B);

例如:查询出那些用户编号在学生表的学生编程里出现过的用户资料。

select * from users where uid in (select sid from students);

3.exists与in的区别

经过sql改变,二者是可以达到同一个目标的:

例如:上例可以改写用exists实现。

select * from users where  exists (select sid from students where sid = users.uid)

那么什么时候用exists 或者in呢?

如果查询的两个表大小相当,那么用in和exists差别不大。 如果两个表中一个较小,一个是大表,则子查询表大的用exists,子查询表小的用in。

not in 和not exists如果查询语句使用了not in 那么内外表都进行全表扫描,没有用到索引;而not extsts 的子查询依然能用到表上的索引。所以无论那个表大,用not exists都比not in要快。