MySQL:使用 UNION 与多个查询
我很想知道UNION
是否比运行多个查询更好。
如果是这样,是否有时多个查询会更快或出于其他原因而成为首选?
I'm interested to know if a UNION
is better than running multiple queries.
If so, are there times that multiple queries would be faster or preferred for other reasons?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
UNION ALL
并且不排序输出,那么UNION 的性能应该与
假设查询是多个单独查询的性能
与您
UNION
组合在一起的那些相同。UNION ALL
并对数据进行排序,显然您会施加一些开销(尽管可能比您在其中排序您的应用程序要少)。
ALL
关键字,MySQL 将执行以下额外工作DISTINCT
-ing 你的结果。同样,这会带来额外的开销虽然可能比自己做的要少。
UNION ALL
and don't sort the output, then theperformance of UNION should be more-or-less the same as the
performance of multiple separate queries assuming the queries are
identical to the ones you're
UNION
-ing together.UNION ALL
and sort the data, obviously you're imposing some overhead(although probably less than if you sorted in it your application).
ALL
keyword, MySQL will do the extra work ofDISTINCT
-ing your results. Again, this imposes extra overheadalthough probably less than doing it yourself.
你问它是否“更好” - 我假设你指的是“性能方面”?
如果速度影响很小,您可能希望使用多个查询来保持代码更具可读性;而不是在一个联合中处理多个查询、做不同的事情。
当然,取决于用例。但从长远来看,可读且可理解的代码在更大的项目中可能是有价值的
You ask if it "is better" - I assume you are referring to "performance-wise"?
If the speed impact is minimal, you might want to prefer multiple queries to keep your code more readable; instead of dealing with multiple queries, doing different things, in one union.
Depends on the use case, for sure. But readable and understandable code might have it's worth in a bigger project in the long term