mysql关于select where in的效率

很多大牛公司建议select where in中不要超过200,有的说不要超过500.
那么问题来了,使用子查询的时候如果结果级超过了500呢。
今天做了个测试

下面是测试结果,分别是两个语句查询10次所用的时间

select * from cp_bill_info where id in(select id from cp_bill_info where id< 501)
第*次查询耗时
1 0.434 s
2 0.468 s
3 0.456 s
4 0.460 s
5 0.451 s
6 0.435 s
7 0.427 s
8 0.481 s
9 0.482 s
10 0.520 s

select * from cp_bill_info where id in(1,2,3,……500)

第*次查询耗时
1 0.559 s
2 0.565 s
3 0.554 s
4 0.549 s
5 0.550 s
6 0.550 s
7 0.541 s
8 0.493 s
9 0.562 s
10 0.531 s

从结果来看用子查询的效率要优于直接写入查询范围。
另外还测试了

select * from cp_bill_info where id in(select id from cp_bill_info where id< 201)
select * from cp_bill_info where id in(select id from cp_bill_info where id< 101)
select * from cp_bill_info where id in(select id from cp_bill_info where id< 1001)

10次的耗时也维持在0.4**s也就是说子查询对于范围的影响很小。
但是使用写入查询范围的方式,当范围越多时,耗时会随之增加。

select * from cp_bill_info where id in(1,2,3,……1000)

用时在0.8**s。

select * from cp_bill_info where id in(1,2,3,……100)
select * from cp_bill_info where id in(1,2,3,……200)

比500的范围缩小用时在0.03左右。

总结:select where in使用子查询时,子查询中结果集的大小对查询速度影响很小。但是直接写入查询范围的时候最好控制在500个以内,越多效率越低

原文地址:https://www.cnblogs.com/T8888/p/14440524.html