# 建存储过程给表 student1,插入1000条数据 dropprocedure if exists addStudent1; createprocedure addStudent1() BEGIN declare idx int; set idx =1; while idx <=1000 DO insertinto student1 values(null, concat('student-', idx)); set idx = idx +1; end while; end;
# 建存储过程给表 student2,插入100000条数据 dropprocedure if exists addStudent2; createprocedure addStudent2() BEGIN declare idx int; set idx =1; while idx <=100000 DO insertinto student2 values(null, concat('student-', idx)); set idx = idx +1; end while; end;
call addStudent2();
select*from student2;
in 与 exists 的查询 SQL
1 2 3 4
selectcount(1) from student1 where sname in (select sname from student2); selectcount(1) from student1 whereexists (select sname from student2 where student2.sname = student1.sname); selectcount(1) from student2 where sname in (select sname from student1); selectcount(1) from student2 whereexists (select sname from student1 where student2.sname = student1.sname);
执行时间:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
[SQL] selectcount(1) from student1 where sname in (select sname from student2); 受影响的行: 0 时间: 0.092s
[SQL] selectcount(1) from student1 whereexists (select sname from student2 where student2.sname = student1.sname); 受影响的行: 0 时间: 0.076s
[SQL] selectcount(1) from student2 where sname in (select sname from student1); 受影响的行: 0 时间: 14.820s
[SQL] selectcount(1) from student2 whereexists (select sname from student1 where student2.sname = student1.sname); 受影响的行: 0 时间: 15.144s
selectcount(1) from student1 where sname notin (select sname from student2); selectcount(1) from student1 wherenotexists (select sname from student2 where student2.sname = student1.sname); selectcount(1) from student2 where sname notin (select sname from student1); selectcount(1) from student2 wherenotexists (select sname from student1 where student2.sname = student1.sname);
执行时间:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
[SQL] selectcount(1) from student1 where sname notin (select sname from student2); 受影响的行: 0 时间: 0.079s
[SQL] selectcount(1) from student1 wherenotexists (select sname from student2 where student2.sname = student1.sname); 受影响的行: 0 时间: 0.075s
[SQL] elect count(1) from student2 where sname notin (select sname from student1); 受影响的行: 0 时间: 15.797s
[SQL] selectcount(1) from student2 wherenotexists (select sname from student1 where student2.sname = student1.sname); 受影响的行: 0 时间: 15.160s
结论:not exists 性能高于 not in
索引影响
给 student1、student2 sname 字段,加上索引,上述结论仍然成立。
1 2
create index idx_1 on student1(sname); create index idx_2 on student2(sname);