Sql Server資料庫之多表查詢
阿新 • • 發佈:2019-01-13
一.連線查詢
概念:根據兩個表或多個表的列之間的關係,從這些表中查詢資料
目的:實現多表查詢操作
語法:From join_table join_type join_table[ON(join_condition)]
join_table:連線的表名
join_type:連線型別
join_condition:連線條件
連線型別:內連線,外連線,交叉連線
二.內連線
1.等值連線
概念:在連線條件中使用"="運算子,其查詢結果中列出被連線表中的所有列,包括其中的重複列
示例:
1 createtable student 2 ( 3 studentId int not null primary key, 4 studentName nvarchar(20) not null, 5 classId int not null 6 ) 7 create table class 8 ( 9 classId int not null primary key, 10 className nvarchar(20) not null 11 ) 12 insert into student values(1,'岳雲鵬',1);13 insert into student values(2,'郭德綱',1); 14 insert into student values(3,'郭麒麟',1); 15 insert into student values(4,'孫越',2); 16 insert into student values(5,'于謙',2); 17 insert into student values(6,'閻鶴翔',2); 18 insert into class values(1,'逗哏班'); 19 insert into class values(2,'捧哏班'); 20 select *from student s inner join class c on s.classId = c.classId
2.不等值連線
概念:在連線條件中使用除等號之外的運算子
示例:
1 select * from student s inner join class c on s.classId != c.classId
三.外連結
1.左連線
左表結構:
右表結構:
左連線查詢:
select * from student s left join class c on s.classId = c.classId
查詢結果:
總結:左連線:返回左表中的所有行,如果左錶行在右表中沒有匹配行,則結果中右表中的列返回控制
2.右連線
右連線查詢:
select * from student s right join class c on s.classId = c.classId
查詢結果:
總結:右連線:恰與左連線相反,返回右表中的所有行,如果右表中行在左表中沒有匹配行,則結果中左表中的列返回空值。
3.全連線
全連線查詢
select * from student s right join class c on s.classId = c.classId
查詢結果
總結:全連線:返回左表和右表中的所有行,當某行在另一表中沒有匹配行,則靈異表中的列返回空值
四.交叉連線(笛卡爾積)
1.不帶where子句
執行交叉連線:
select * from student cross join class
查詢結果:
2.帶where子句
執行交叉連線:
select * from student s cross join class c where s.classId = c.classId
查詢結果: