多个查询与联合多个查询,哪个会更快?
顾名思义,使用多个或的查询会更快,还是使用联合连接的多个查询的查询会更快?为了简单起见,我只连接了两个表,但连接中可以有更多表。
例如,
select isbn, booktitle from book as b left join publisher as p
on b.publisherid = p.publisherid
where
booktitle like '%mysql%' or
isbn like '%mysql%' or
publishername like '%mysql%'
与
select isbn, booktitle from book as b left join publisher as p
on b.publisherid = p.publisherid
where
booktitle like '%mysql%'
union
select isbn, booktitle from book as b left join publisher as p
on b.publisherid = p.publisherid
where
isbn like '%mysql%'
union
select isbn, booktitle from book as b left join publisher as p
on b.publisherid = p.publisherid
where
publishername like '%mysql%'
As the name suggests, a query with multiple or will be faster or a query with multiple query joined with union will be faster? I have joined only two tables to make it simple but there can be more tables in join.
for example,
select isbn, booktitle from book as b left join publisher as p
on b.publisherid = p.publisherid
where
booktitle like '%mysql%' or
isbn like '%mysql%' or
publishername like '%mysql%'
vs
select isbn, booktitle from book as b left join publisher as p
on b.publisherid = p.publisherid
where
booktitle like '%mysql%'
union
select isbn, booktitle from book as b left join publisher as p
on b.publisherid = p.publisherid
where
isbn like '%mysql%'
union
select isbn, booktitle from book as b left join publisher as p
on b.publisherid = p.publisherid
where
publishername like '%mysql%'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不知道你的工会会更快。您必须扫描并加入 3 次,而在第一次中,您只需扫描一次,并且对于每个加入的记录,您都可以应用条件。
I don't see how your union's would be faster. You're having to scan and join 3 times, where as in the first one, you're only scanning once, and for each joined record you can apply the criteria.
最上面的一个会更有效,因为您只查询数据一次。也就是说,如果您查询不会返回的数据,最好将这些条件放在
WHERE
的IN
子句中。在您提供的示例中,它看起来像这样:通过过滤列(在本例中为发布者名称)上的适当索引,MySQL 将优化每个部分并更有效地组合它们。
The top one will be more efficient since you're only querying the data once. That said, if you're querying against data you will not be returning, it's even better to put those criteria in an
IN
clause in theWHERE
. In your provided example, it would look like this:With proper indexes on the filtering columns (publishername, in this case), MySQL will optimize each piece and combine them much more efficiently.
第二个会更快。
分析如下:
http://books.google.com.sg/books?id=iaCCQ13_zMIC&pg=PT118&lpg=PT118&dq=In+this+example,+MySQL+uses+the+ExpireTime+index+to+ fetch+a+set+of+rows&source=bl&ots=3FJ1-70Hq3&sig=V_0z7nSV7_hGwW_fC8IWmFI7ZLw&hl=en&sa=X&ei=Xx1uUan5IsulrQfh04GIBA&ved=0CDQQ6AEwAA
The second one will be faster.
Here is the analysis:
http://books.google.com.sg/books?id=iaCCQ13_zMIC&pg=PT118&lpg=PT118&dq=In+this+example,+MySQL+uses+the+ExpireTime+index+to+fetch+a+set+of+rows&source=bl&ots=3FJ1-70Hq3&sig=V_0z7nSV7_hGwW_fC8IWmFI7ZLw&hl=en&sa=X&ei=Xx1uUan5IsulrQfh04GIBA&ved=0CDQQ6AEwAA