看到网上好多的文章,关于in 和exists,我自己专门去校验了一下,自己通过存储过程,循环增加了10万条数据,
//创建表
drop table if exists tb_test;
create table tb_test(
id int PRIMARY key auto_increment not null,
name varchar(20)
)
//存储过程
delimiter &&
BEGIN
declare j int DEFAULT 0;
while j<i DO
insert into tb_test(name) values('王威振');
set j=j+1;
end WHILE;
end &&
delimiter
然后进行查询
select * from tb_test where exists(select name from tb_test name = '王威振')
select * from tb_test where name in ('王威振')
其实exists 和in 要根据表的大小,查询tb_test 数据大于条件中查询的数据用in花费的成本低,否则用exists.
可以通过 explain format = json 查看语句的执行计划,然后看到花费的成本。
总的来说,select * from test t where t.id in (select id from tb ) 如果test 表数据>tb 用in