Subqueries vs joins

前端 未结 14 1875
闹比i
闹比i 2020-11-22 16:10

I refactored a slow section of an application we inherited from another company to use an inner join instead of a subquery like:

WHERE id IN (SELECT id FROM          


        
相关标签:
14条回答
  • 2020-11-22 16:42

    With a subquery, you have to re-execute the 2nd SELECT for each result, and each execution typically returns 1 row.

    With a join, the 2nd SELECT returns a lot more rows, but you only have to execute it once. The advantage is that now you can join on the results, and joining relations is what a database is supposed to be good at. For example, maybe the optimizer can spot how to take better advantage of an index now.

    0 讨论(0)
  • 2020-11-22 16:47

    You are running the subquery once for every row whereas the join happens on indexes.

    0 讨论(0)
  • 2020-11-22 16:47

    Look at the query plan for each query.

    Where in and Join can typically be implemented using the same execution plan, so typically there is zero speed-up from changing between them.

    0 讨论(0)
  • 2020-11-22 16:50

    Run the explain-plan on each version, it will tell you why.

    0 讨论(0)
  • 2020-11-22 16:52

    The subquery was probably executing a "full table scan". In other words, not using the index and returning way too many rows that the Where from the main query were needing to filter out.

    Just a guess without details of course but that's the common situation.

    0 讨论(0)
  • 2020-11-22 16:56

    Usually its the result of the optimizer not being able to figure out that the subquery can be executed as a join in which case it executes the subquery for each record in the table rather then join the table in the subquery against the table you are querying. Some of the more "enterprisey" database are better at this, but they still miss it sometimes.

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