Does the order of tables in a join matter, when LEFT (outer) joins are used?

前端 未结 3 1142
情书的邮戳
情书的邮戳 2020-12-18 01:54

I would like to confirm that the SQL query

SELECT ....
  FROM apples,
       oranges
       LEFT JOIN kiwis ON kiwis.orange_id = oranges.id,
       bananas
          


        
相关标签:
3条回答
  • 2020-12-18 02:15

    It is the same but it is ambiguous as hell with the implicit CROSS JOINs. Use explicit JOINS.

    If you are joining in the WHERE clause then the results may differ because joins and filters are mixed up.

    SELECT ....
      FROM apples a
           JOIN
           bananas b ON ...
           JOIN 
           oranges o ON ...
           LEFT JOIN
           kiwis k ON k.orange_id = o.id
     WHERE (filters only)
    

    Notes:

    • INNER JOINS and CROSS JOINS are commutative and associative: order does not matter usually.
    • OUTER JOINS are not, which you identified
    • SQL is declarative: you tell the optimiser what you want, not how to do it. This removes JOIN order considerations (subject to the previous 2 items)
    0 讨论(0)
  • 2020-12-18 02:25

    The situation is summarized at Controlling the Planner with Explicit JOIN Clauses. Outer joins don't get reordered, inner ones can be. And you can force a particular optimizer order by dropping *join_collapse_limit* before running the query, and just putting things in the order you want them it. That's how you "hint" at the database in this area.

    In general, you want to use EXPLAIN to confirm what order you're getting, and that can sometimes be used to visually confirm that two queries are getting the same plan.

    0 讨论(0)
  • 2020-12-18 02:42

    I've done SQL for donkeys years, and in all my experience, the table order does not matter. The database will look at the query as a whole and create the optimal query plan. That is why database companies employ many people with PhD in query plan optimisations.

    The database vendor would commit commercial suicide if it optimised by the order in which you personally listed the SQL in your query.

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