SQL Server高級內容之子查詢和表鏈接


1.子查詢概念

   (1)就是在查詢的where子句中的判斷依據是另一個查詢的結果,如此就構成了一個外部的查詢和一個內部的查詢,這個內部的查詢就是自查詢。

   (2)自查詢的分類

  1)獨立子查詢

     ->獨立單值(標量)子查詢  (=)

 1 Select
 2 
 3     testID,stuID,testBase,testBeyond,testPro 
 4 
 5 from Score
 6 
 7     where stuID=(
 8     
 9         select stuID from Student where stuName=’Kencery’
10 
11        )

   ->獨立多值子查詢  (in)

 1 Select
 2 
 3     testID,stuID,testBase,testBeyond,testPro 
 4 
 5 from Score
 6 
 7     where stuID in(
 8 
 9         select stuID from Student where stuName=’Kencery’
10 
11     )

   2)相關子查詢

   (3)寫子查詢的注意事項

  1)子查詢用一個圓括號闊氣,有必要的時候需要為表取別名,使用“as 名字”即可。

2.表連接\

  (1)表鏈接就是將多個表合成為一個表,但是不是向union一樣做結果集的合並操作,但是表鏈接可以將不同的表合並,並且共享字段。

  (2)表連接之交叉連接 (cross join)

    1)創建兩張表

 1  use Test
 2 
 3 go
 4 
 5 create table testNum1
 6 
 7 (
 8 
 9     Num1 int
10 
11 );
12 
13 create table testNum2
14 
15 (
16 
17     Num2 int
18 
19 );
20 
21 insert into testNum1 values(1),(2),(3)
22 
23 insert into testNum2 values(4),(5)

    2) 執行交叉連接的SQL語句

      select * from testNum1 cross join testNum2

    3)注解

      交叉連接就是將第一張表中的所有數據與第二張表中的所有數據挨個匹配一次,構成一個新表。

    4)自交叉的實現

      執行插入SQL語句:

      insert into testNum1 values(4),(5),(6),(7),(8),(9),(0)

      執行自交叉的SQL語句:

      select t1.num1,t2.num2 from testNum1 as t1 cross join testNum2 as t2

    5)另外一種寫法:

      select * from testNum1,testNum2不提倡使用,首先是有比較新的語法,缺陷是逗號不明確,並且這個語法與內連接和外連接都可以使用,如果使用join聲明,那么語法錯誤的時候可以報錯,但是使用這個語法,可能因為部分語法的錯誤,會被SQL Server解釋為交叉連接而跳過這個語法的檢查

   (3)表連接之內連接

     1)內鏈接是在交叉連接的基礎之上添加一個約束條件

     2)語法:select * from 表1 inner join 表2 on 表1.字段=2.字段

 1 Select  s1.stuID,
 2 
 3     s1.stuName,
 4 
 5     s1.stuSex,
 6 
 7     s2.testBase,
 8 
 9     s2.testBeyond 
10 
11         from Student as s1
12 
13     inner join Score as s2
14 
15         on s1.stuID=s2.stuID
16 
17     where s1.stuIsDel=0;

   (4)表連接之外連接

     1)執行下面的SQL語句

 1 create table tblMain
 2 
 3 (
 4 
 5     ID int,
 6 
 7     name nvarchar(20),
 8 
 9     fid int
10 
11 );
12 
13 create table tblOther
14 
15 (
16 
17     ID int,
18 
19     name nvarchar(20)
20 
21 )
22 
23 insert into tblMain values(1,'張三',1),(2,'李四',2)
24 
25 insert into tblOther values(1,'C++'),(2,'.net'),(3,'java')
26 
27 select * from 
28 
29     tblMain as t1
30 
31        inner join 
32 
33     tblOther as t2
34 
35         on 
36 
37     t1.fid=t2.id 

 

     2)在內連接的基礎之上,在做一件事兒,就是將tblOther中的Java也顯示出來,這時候就要使用到外連接,外連接有左外連接和右外連接。

     3)左連接和右連接有什么區別呢??區別就是**連接就是以**表為主表,在內連接的基礎之上,將沒有數據的那張表的信息還是要顯示出來供用戶查看,那么這個主表就是要顯示的那張表。左外連接和右外連接的分別是在前面的這張表就是左表,在后面的那張表就是右表,左連接使用left join ,有連接使用right join

     4)上面重新執行下面的SQL語句,就會顯示出tblOther表中的Java

1 select * from 
2 
3     tblMain as t1
4 
5         right join tblOther as t2
6 
7     on t1.fid=t2.id 

 

 

 

                              相信自己,你就是下一個奇跡(Kencery)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM