Join vs. sub-query

前端 未结 19 2054
广开言路
广开言路 2020-11-21 05:05

I am an old-school MySQL user and have always preferred JOIN over sub-query. But nowadays everyone uses sub-query, and I hate it; I don\'t know why.

19条回答
  •  心在旅途
    2020-11-21 05:06

    First of all, to compare the two first you should distinguish queries with subqueries to:

    1. a class of subqueries that always have corresponding equivalent query written with joins
    2. a class of subqueries that can not be rewritten using joins

    For the first class of queries a good RDBMS will see joins and subqueries as equivalent and will produce same query plans.

    These days even mysql does that.

    Still, sometimes it does not, but this does not mean that joins will always win - I had cases when using subqueries in mysql improved performance. (For example if there is something preventing mysql planner to correctly estimate the cost and if the planner doesn't see the join-variant and subquery-variant as same then subqueries can outperform the joins by forcing a certain path).

    Conclusion is that you should test your queries for both join and subquery variants if you want to be sure which one will perform better.

    For the second class the comparison makes no sense as those queries can not be rewritten using joins and in these cases subqueries are natural way to do the required tasks and you should not discriminate against them.

提交回复
热议问题