Should I use one big SQL Select statement or several small ones?

后端 未结 7 611
一整个雨季
一整个雨季 2021-01-17 08:54

I\'m building a PHP page with data sent from MySQL.

Is it better to have

  • 1 SELECT query with 4 table joins, or
  • 4 small SELE
相关标签:
7条回答
  • 2021-01-17 09:17

    Generally, it's better to have one SELECT statement. One of the main reasons to have databases is that they are fast at processing information, particularly if it is in the format of query.

    If there is any drawback to this approach, it's that there are some kinds of analysis that you can't do with one big SELECT statement. RDBMS purists will insist that this is a database design problem, in which case you are back to my original suggestion.

    0 讨论(0)
  • 2021-01-17 09:26

    You should run a profiling tool if you're truly worried cause it depends on many things and it can vary but as a rule its better to have fewer queries being compiled and fewer round trips to the database.

    Make sure you filter things as well as you can using your where and join on clauses.

    But honestly, it usually doesn't matter since you're probably not going to be hit all that hard compared to what the database can do, so unless optimization is your spec you should not do it prematurely and do whats simplest.

    0 讨论(0)
  • 2021-01-17 09:27

    When you use JOINs instead of multiple queries, you allow the database to apply its optimizations. You also are potentially retrieving rows that you don't need (if you were to replace an INNER join with multiple selects), which increases the network traffic between your app server and database server. Even if they're on the same box, this matters.

    0 讨论(0)
  • 2021-01-17 09:27

    I would say 1 query with the join. This way you need to hit the server only once. And if your tables are joined with indexes, it should be fast.

    0 讨论(0)
  • 2021-01-17 09:30

    It might depend on what you do with the data after you fetch it from the DB. If you use each of the four results independently, then it would be more logical and clear to have four separate SELECT statements. On the other hand, if you use all the data together, like to create a unified row in a table or something, then I would go with the single SELECT and JOINs.

    I've done a bit of PHP/MySQL work, and I find that even for queries on huge tables with tons of JOINs, the database is pretty good at optimizing - if you have smart indexes. So if you are serious about performance, start reading up on query optimization and indexing.

    0 讨论(0)
  • 2021-01-17 09:30

    Be careful when dealing with a merge table however. It has been my experience that although a single join can be good in most situations, when merge tables are involved you can run into strange situations.

    0 讨论(0)
提交回复
热议问题