开发者

Using a single joined query instead of multiple queries for performance?

开发者 https://www.devze.com 2023-01-27 16:46 出处:网络
Suppose I have a database which contains blog posts which have tags and I want to retrieve a blog post with its tags.

Suppose I have a database which contains blog posts which have tags and I want to retrieve a blog post with its tags.

I can do two queries:

SELECT title, text, date 
  FROM POSTS 
 WHERE id = 1

and

SELECT tag 
  FROM TAGS 
 WHERE post_id = 1

However I can also do it in a single query:

SELECT title, text, date, tag 
  FROM POSTS, TAGS 
 WHERE posts.id = 1 
  AND tags.post_id = posts.id

The latter is a bit wasteful, because it transfers the same title, text and date columns as many times as many tags the blog post have, but it may be faster, because there is only one trip to the server.

Is there some alternative for the latter query which avoids transferring duplicate data? Or is it n开发者_C百科ot a big deal and I should use it anyway, because transferring a few hundred unused extra bytes is cheaper than making two separate queries?


MySQL optimization isn't quite as straightforward as this. You'll find that sometimes multiple queries (possibly with a temp table in the middle) is much faster than a single query, especially with complex joins / aggregations going on. So, don't assume that a single query will always be faster, because it won't.

However, a single query is often just as fast or faster than multiple queries, and it expresses what you're doing much more succinctly. Don't worry about a handful of bytes across the wire, they are trivial in comparison to everything else that's going on.


Rather make a single trip to the server, than a trip per posts entry.

Trust me, you will see the performance gain.

I single query to retrieve data is more often than not a better solution than using round trips from the Client to Server.

0

精彩评论

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