开发者

MySQL: using UNION vs multiple queries

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?


  • If you use UNION ALL and don't sort the output, then the performance 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.
  • If you use UNION ALL and sort the data, obviously you're imposing some overhead (although probably less than if you sorted in it your application).
  • If you leave out the ALL keyword, MySQL will do the extra work of DISTINCT-ing your results. Again, this imposes extra overhead although 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜