union和in哪个效率高

时间:2022-04-24 19:57:36

一直都认为是in的效率要高,但是这次确有点蒙圈。

SELECT * FROM runinfo WHERE status in (0,2,1,3,4,7,9,10);  

这个查询的效率是,经常是1秒多。

mysql> SELECT * FROM runinfo WHERE status in (0,2,1,3,4,7,9,10);

106 rows in set (1.20 sec)

 

替换成下面这种写法之后,

SELECT * FROM runinfo WHERE status = 0
union
SELECT * FROM runinfo WHERE status = 1
union
SELECT * FROM runinfo WHERE status = 2
union
SELECT * FROM runinfo WHERE status = 3
union
SELECT * FROM runinfo WHERE status = 4
union
SELECT * FROM runinfo WHERE status = 7
union
SELECT * FROM runinfo WHERE status = 9
union
SELECT * FROM runinfo WHERE status = 10  

效率有很大的提升。

mysql>

108 rows in set (0.02 sec)

 

具体的原因我也说不上来,其中status字段有建索引,这个字段会有一些更新。

先做记录,慢慢再搞清楚这件事情吧。