我有一个文章表,查询多条文章记录
id是主键,还有若干像title,content,author之类的字段(post表记录300W+)
select * from post where id in (id1,id2,id3,id4)
和
select * from post where id = id1 union select * from post where id = id2 union select * from post where id = id3 union select * from post where id = id4
的效率哪一个更高?(id的个数从1-20条不等)
对于你这类的简单判断范围的查询,使用IN的效率要高于UNION。
在有索引的字段上使用,这两者执行的过程几乎一样,所以差不不大。
但是对于没有索引的字段,使用UNION意味着要比使用IN多扫描N次表,也就造成多N倍的时间。(这里的N代表的就是ID的个数)
所以总和来说,这种场景下使用IN更为合适。