Microsoft SQL Server 交叉连接
示例
Acrossjoin是笛卡尔联接,表示两个表的笛卡尔乘积。此联接不需要任何条件即可联接两个表。左表中的每一行将连接到右表中的每一行。交叉联接的语法:
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
请注意,还有其他方法可以应用CROSSJOIN。这是无条件的“旧式”联接(自ANSISQL-92起不推荐使用),导致交叉/笛卡尔联接:
SELECT * FROM @Animal, @AnimalSound;
由于“始终为真”的连接条件,该语法也可以使用,但是不建议这样做CROSSJOIN,为便于阅读,应避免使用显式语法。
SELECT * FROM @Animal JOIN @AnimalSound ON 1=1