Microsoft SQL Server 内部联接
示例
Innerjoin根据一个或多个条件(使用ON关键字指定)仅返回在两个表中匹配/存在的记录/行。这是最常见的联接类型。的一般语法为innerjoin:
SELECT * FROM table_1 INNER JOIN table_2 ON table_1.column_name = table_2.column_name
也可以简化为JOIN:
SELECT * FROM table_1 JOIN table_2 ON table_1.column_name = table_2.column_name
例
/* 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, 'Trumpets'); /* Sample data prepared. */ SELECT * FROM @Animal JOIN @AnimalSound ON @Animal.AnimalId = @AnimalSound.AnimalId;
AnimalId Animal AnimalSoundId AnimalId Sound ----------- -------------------- ------------- ----------- -------------------- 1 Dog 1 1 Barks 2 Cat 2 2 Meows 3 Elephant 3 3 Trumpets
将内部联接与左侧外部联接一起使用(不存在替代)
该查询将返回表1中的数据,其中与带有条件键的table2匹配的字段和与带条件键的Table2进行比较时不在表1中的数据
select * from Table1 t1 inner join Table2 t2 on t1.ID_Column =t2.ID_Column left join Table3 t3 on t1.ID_Column =t3.ID_Column wheret2.column_name= column_value andt3.ID_Columnis null order by t1.column_name;