SQL Server高級(jí)內(nèi)容:子查詢和表鏈接
1.子查詢概念
(1)就是在查詢的where子句中的判斷依據(jù)是另一個(gè)查詢的結(jié)果,如此就構(gòu)成了一個(gè)外部的查詢和一個(gè)內(nèi)部的查詢,這個(gè)內(nèi)部的查詢就是自查詢。
(2)自查詢的分類
1)獨(dú)立子查詢
->獨(dú)立單值(標(biāo)量)子查詢 (=)
- Select
- testID,stuID,testBase,testBeyond,testPro
- from Score
- where stuID=(
- select stuID from Student where stuName=’Kencery’
- )
->獨(dú)立多值子查詢 (in)
- Select
- testID,stuID,testBase,testBeyond,testPro
- from Score
- where stuID in(
- select stuID from Student where stuName=’Kencery’
- )
2)相關(guān)子查詢
(3)寫子查詢的注意事項(xiàng)
1)子查詢用一個(gè)圓括號(hào)闊氣,有必要的時(shí)候需要為表取別名,使用“as 名字”即可。
2.表連接\
(1)表鏈接就是將多個(gè)表合成為一個(gè)表,但是不是向union一樣做結(jié)果集的合并操作,但是表鏈接可以將不同的表合并,并且共享字段。
(2)表連接之交叉連接 (cross join)
1)創(chuàng)建兩張表
- use Test
- go
- create table testNum1
- (
- Num1 int
- );
- create table testNum2
- (
- Num2 int
- );
- insert into testNum1 values(1),(2),(3)
- insert into testNum2 values(4),(5)
2) 執(zhí)行交叉連接的SQL語(yǔ)句
select * from testNum1 cross join testNum2
3)注解
交叉連接就是將第一張表中的所有數(shù)據(jù)與第二張表中的所有數(shù)據(jù)挨個(gè)匹配一次,構(gòu)成一個(gè)新表。
4)自交叉的實(shí)現(xiàn)
執(zhí)行插入SQL語(yǔ)句:
insert into testNum1 values(4),(5),(6),(7),(8),(9),(0)
執(zhí)行自交叉的SQL語(yǔ)句:
select t1.num1,t2.num2 from testNum1 as t1 cross join testNum2 as t2
5)另外一種寫法:
select * from testNum1,testNum2不提倡使用,首先是有比較新的語(yǔ)法,缺陷是逗號(hào)不明確,并且這個(gè)語(yǔ)法與內(nèi)連接和外連接都可以使用,如果使用join聲明,那么語(yǔ)法錯(cuò)誤的時(shí)候可以報(bào)錯(cuò),但是使用這個(gè)語(yǔ)法,可能因?yàn)椴糠终Z(yǔ)法的錯(cuò)誤,會(huì)被SQL Server解釋為交叉連接而跳過這個(gè)語(yǔ)法的檢查
(3)表連接之內(nèi)連接
1)內(nèi)鏈接是在交叉連接的基礎(chǔ)之上添加一個(gè)約束條件
2)語(yǔ)法:select * from 表1 inner join 表2 on 表1.字段=表2.字段
- Select s1.stuID,
- s1.stuName,
- s1.stuSex,
- s2.testBase,
- s2.testBeyond
- from Student as s1
- inner join Score as s2
- on s1.stuID=s2.stuID
- where s1.stuIsDel=0;
(4)表連接之外連接
1)執(zhí)行下面的SQL語(yǔ)句
- create table tblMain
- (
- ID int,
- name nvarchar(20),
- fid int
- );
- create table tblOther
- (
- ID int,
- name nvarchar(20)
- )
- insert into tblMain values(1,'張三',1),(2,'李四',2)
- insert into tblOther values(1,'C++'),(2,'.net'),(3,'java')
- select * from
- tblMain as t1
- inner join
- tblOther as t2
- on
- t1.fid=t2.id
2)在內(nèi)連接的基礎(chǔ)之上,在做一件事兒,就是將tblOther中的Java也顯示出來(lái),這時(shí)候就要使用到外連接,外連接有左外連接和右外連接。
3)左連接和右連接有什么區(qū)別呢??區(qū)別就是**連接就是以**表為主表,在內(nèi)連接的基礎(chǔ)之上,將沒有數(shù)據(jù)的那張表的信息還是要顯示出來(lái)供用戶查看,那么這個(gè)主表就是要顯示的那張表。左外連接和右外連接的分別是在前面的這張表就是左表,在后面的那張表就是右表,左連接使用left join ,有連接使用right join。
4)上面重新執(zhí)行下面的SQL語(yǔ)句,就會(huì)顯示出tblOther表中的Java。
原文鏈接:http://www.cnblogs.com/hanyinglong/archive/2013/03/06/2945380.html
【編輯推薦】