SQL JOIN: is there a difference between USING, ON or WHERE?

前端 未结 6 1832
渐次进展
渐次进展 2020-11-22 00:11

I was wondering if there is any difference in the way SQL performs on these join statements:

SELECT * FROM a,b WHERE a.ID = b.ID

SELECT * FROM a JOIN b ON a         


        
6条回答
  •  迷失自我
    2020-11-22 01:01

    No one has provided an answer about the USING(...) syntax yet.

    While these two queries are equivalent logically, and also from the perspective of most modern optimisers:

    SELECT * FROM a, b WHERE a.id = b.id
    SELECT * FROM a JOIN b ON a.id = b.id
    

    This one has a slightly different semantics:

    SELECT * FROM a JOIN b USING (id)
    

    Assuming the following schema:

    CREATE TABLE a (id int, a1 int, a2 int);
    CREATE TABLE b (id int, b1 int, b2 int);
    

    The first two queries will have their asterisks expanded to:

    SELECT a.id, a.a1, a.a2, b.id, b.a1, b.a2 FROM ...
    

    Whereas the third query will have its asterisk expanded to:

    SELECT coalesce(a.id, b.id) AS id, a.a1, a.a2, b.a1, b.a2 FROM ...
    

    This is quite different for various reasons, including:

    • The number of projected columns is now 5 instead of 6. This could get in the way when you use UNION or other set operations. Which you probably don't, with an asterisk.
    • There is no longer a qualified (and duplicate) a.id or b.id column, only an id column. While PostgreSQL still allows for qualifying references to id (e.g. when needing to disambiguate them), Oracle for example doesn't.
    • As a consequence, in the third query with the USING(...) syntax, projecting a.* or b.* is no longer possible in Oracle.

提交回复
热议问题