交叉加入

A cross join 是笛卡爾連線,意思是兩個表的笛卡爾積。此連線不需要任何條件來連線兩個表。左表中的每一行都將連線到右表的每一行。交叉連線的語法:

SELECT * FROM table_1
CROSS JOIN table_2 

例:

/* Sample data. */
DECLARE @Animal table (
    AnimalId Int IDENTITY,
    Animal Varchar(20)
);

DECLARE @AnimalSound table (
    AnimalSoundId Int IDENTITY,
    AnimalId Int,
    Sound Varchar(20)
);

INSERT INTO @Animal (Animal) VALUES ('Dog');
INSERT INTO @Animal (Animal) VALUES ('Cat');
INSERT INTO @Animal (Animal) VALUES ('Elephant');

INSERT INTO @AnimalSound (AnimalId, Sound) VALUES (1, 'Barks');
INSERT INTO @AnimalSound (AnimalId, Sound) VALUES (2, 'Meows');
INSERT INTO @AnimalSound (AnimalId, Sound) VALUES (3, 'Trumpet');
/* Sample data prepared. */

SELECT 
    * 
FROM 
    @Animal 
    CROSS JOIN @AnimalSound;

結果:

AnimalId    Animal               AnimalSoundId AnimalId    Sound
----------- -------------------- ------------- ----------- --------------------
1           Dog                  1             1           Barks
2           Cat                  1             1           Barks
3           Elephant             1             1           Barks
1           Dog                  2             2           Meows
2           Cat                  2             2           Meows
3           Elephant             2             2           Meows
1           Dog                  3             3           Trumpet
2           Cat                  3             3           Trumpet
3           Elephant             3             3           Trumpet

請注意,還有其他方法可以應用 CROSS JOIN。這是一個 舊樣式 連線(自 ANSI SQL-92 以來不推薦使用),沒有條件,這導致交叉/笛卡爾連線:

SELECT * 
FROM @Animal, @AnimalSound;

由於始終為真的連線條件,此語法也有效,但為了便於閱讀,不建議使用,應該避免使用顯式的 CROSS JOIN 語法。

SELECT * 
FROM 
    @Animal 
    JOIN @AnimalSound 
        ON 1=1