Which query is the correct way?

后端 未结 1 1891
误落风尘
误落风尘 2020-12-20 04:19

Can somebody please tell me which is the better way, they both produce the same results but which is more \'correct\'?

Personally I feel the first query is easier to

相关标签:
1条回答
  • 2020-12-20 05:08

    The difference between the two queries is the JOIN syntax:

    • The first one use the ANSI-92 JOIN syntax.
    • The second one use the old ANSI-89 JOIN syntax.

    Which is better?

    Both syntaxes are supported by MySQL and SQL Server and other RDBMS as well, and you shouldn't expect any performance difference between the two. They are the same.

    But, it is recommended to use the first one. It is safer in number of ways. For example, if you want to do an INNER JOIN, using the second syntax:

    SELECT *
    FROM Table1 t1, Table2 t2
    WHERE t1.id = t2.id2;
    

    If you forgot the WHERE t1.id = t2.id, the query won't fail. But it will produce a cross join and it will be hard to find out that error. But using the first syntax:

    SELECT *
    FROM Table1 t1 INNER JOIN Table2 t2 ON t1.id = t2.id2;
    

    If you forgot the ON condition, you will get a syntax error. Even if you intended to do a CROSS JOIN it will more readable for other to tell that:

    SELECT *
    FROM Table1 t1 CROSS JOIN Table2 t2 
    

    Than the other syntax.

    Another benefit noted by @Gareth (See the comments below):

    Another massive benefit is the ease of switching between INNER and OUTER joins without having to handle NULL in the WHERE clause.

    For more information see the folowing:

    • Bad habits to kick : using old-style JOINs.

    • Bad habits to kick : using table aliases like (a, b, c) or (t1, t2, t3).

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

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