Join vs. sub-query

前端 未结 19 2015
广开言路
广开言路 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:24

    MSDN Documentation for SQL Server says

    Many Transact-SQL statements that include subqueries can be alternatively formulated as joins. Other questions can be posed only with subqueries. In Transact-SQL, there is usually no performance difference between a statement that includes a subquery and a semantically equivalent version that does not. However, in some cases where existence must be checked, a join yields better performance. Otherwise, the nested query must be processed for each result of the outer query to ensure elimination of duplicates. In such cases, a join approach would yield better results.

    so if you need something like

    select * from t1 where exists select * from t2 where t2.parent=t1.id
    

    try to use join instead. In other cases, it makes no difference.

    I say: Creating functions for subqueries eliminate the problem of cluttter and allows you to implement additional logic to subqueries. So I recommend creating functions for subqueries whenever possible.

    Clutter in code is a big problem and the industry has been working on avoiding it for decades.

提交回复
热议问题