在用 SQL 编写时,我怎么知道我应该使用交叉积(交叉联接、笛卡尔积)还是自然联接?
3 回答
CROSS JOIN
creates all possible pairings of rows from two tables, whether they match or not. You don't use any join condition for a cross product, because the condition would always be true for any pairing.
An example of using CROSS JOIN
: you have tables of ShoeColors and ShoeSizes, and you want to know how many possible combinations there are. SELECT COUNT(*) FROM ShoeColors CROSS JOIN ShoeSizes;
NATURAL JOIN
is just like an INNER JOIN
, but it assumes the condition is equality and applies for all columns names that appear in both tables. I never use NATURAL JOIN
, because I can't assume that just because columns have the same name, that they should be related. That would require a very strict column naming convention, and practically no real-world project has such discipline.
简而言之,交叉连接在两个不同表的行之间执行了笛卡尔积..列名可能匹配也可能不匹配......但在自然连接中,为了执行连接操作,列名是强制性的必须匹配两个表
自然联接是交叉联接,其中条件位于两个表中具有相同名称的列上。
假设您有两个表:A 和 B
>>select * from A;
col1 col2 col3
---------------
1 2 1
1 4 0
>>select * from B;
col1 col2
---------
1 2
1 3
>>select * from A cross join B;
col1 col2 col3 col1_2 col2_2
-----------------------------
1 2 1 1 2
1 2 1 1 3
1 4 0 1 2
1 4 0 1 3
>>select * from A natural join B;
col1 col2 col3
---------------
1 2 1
1 2 1
更多详情请访问我的帖子。https://eduit.nuxaavi.com.mx/2021/10/16/producto-cartesiano-sql/