What is the difference between CROSS JOIN and multiple tables in one FROM?

后端 未结 2 1504
刺人心
刺人心 2021-01-23 05:14

What is the difference?

SELECT a.name, b.name
FROM a, b;

SELECT a.name, b.name
FROM a
CROSS JOIN b;

If there is no difference then why do both

相关标签:
2条回答
  • 2021-01-23 05:56

    The first with the comma is an old style from the previous century.

    The second with the CROSS JOIN is in newer ANSI JOIN syntax.

    And those 2 queries will indeed give the same results.

    They both link every record of table "a" against every record of table "b".
    So if table "a" has 10 rows, and table "b" has 100 rows.
    Then the result would be 10 * 100 = 1000 records.

    But why does that first outdated style still exists in some DBMS?
    Mostly for backward compatibility reasons, so that some older SQL's don't suddenly break.

    Most SQL specialists these days would frown upon someone who still uses that outdated old comma syntax. (although it's often forgiven for an intentional cartesian product)

    A CROSS JOIN is a cartesian product JOIN that's lacking the ON clause that defines the relationship between the 2 tables.

    In the ANSI JOIN syntax there are also the OUTER joins: LEFT JOIN, RIGHT JOIN, FULL JOIN

    And the normal JOIN, aka the INNER JOIN.

    But those normally require the ON clause, while a CROSS JOIN doesn't.

    And example of a query using different JOIN types.

    SELECT *
    FROM jars
    JOIN apples ON apples.jar_id = jars.id
    LEFT JOIN peaches ON peaches.jar_id = jars.id
    CROSS JOIN bananas AS bnns
    RIGHT JOIN crates ON crates.id = jars.crate_id
    FULL JOIN nuts ON nuts.jar_id = jars.id
    WHERE jars.name = 'FruityMix'
    

    The nice thing about the JOIN syntax is that the link criteria and the search criteria are separated.

    While in the old comma style that difference would be harder to notice. Hence it's easier to forget a link criteria.

    SELECT *
    FROM crates, jars, apples, peaches, bananas, nuts
    WHERE apples.jar_id = jars.id
      AND jars.name = 'NuttyFruitBomb'
      AND peaches.jar_id = jars.id(+)
      AND crates.id(+) = jar.crate_id;
    

    Did you notice that the first query has 1 cartesian product join, but the second has 2? That's why the 2nd is rather nutty.

    0 讨论(0)
  • 2021-01-23 06:09

    Both expressions perform a Cartesian product of the two given tables. They are hence equivalent.

    Please note that from SQL style point of view, using JOIN has been the preferred syntax for a long time now.

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