SQL語句多表連接查詢語法


一、外連接

1.左連接  left join 或 left outer join

SQL語句:select * from student left join score on student.Num=score.Stu_id;

2.右連接  right join 或 right outer join

SQL語句:select * from student right join score on student.Num=score.Stu_id;

3.完全外連接  full join 或 full outer join

SQL語句:select * from student full join score on student.Num=score.Stu_id;

通過上面這三種方法就可以把不同的表連接到一起,變成一張大表,之后的查詢操作就簡單一些了。

而對於select * from student,score;則盡量不使用此語句,產生的結果過於繁瑣。

二、內連接 

join 或 inner join

SQL語句:select * from student inner join score on student.Num=score.Stu_id;

此時的語句就相當於:select * from student,score where student.ID=course.ID;

三、交叉連接

cross join,沒有where指定查詢條件的子句的交叉聯接將產生兩表的笛卡爾積。

SQL語句:select * from student cross join score;

四、結構不同的表連接

當兩表為多對多關系的時候,我們需要建立一個中間表student_score,中間表至少要有兩表的主鍵。

SQL語句:select s.Name,C.Cname from student_score as sc left join student as s on s.Sno=sc.Sno left join score as c on c.Cno=sc.Cno

select C_name,grade from student left join score on student.Num=score.Stu_id where name='李五一';

紅色部分即中間表,是集合兩表所有內容的一張總表。

五、UNION操作符用於合並兩個或多個select語句的結果集。

UNION內部的SELECT語句必須擁有相同數量的列,每個列也必須擁有相似的數據類型,每條SELECT語句中的列的順序必須相同。

select Num from student union select Stu_id from score;

union操作符是默認查重的,如果允許重復的值,就可以使用union all 。對於兩張結構相同的表,union也可以把他們合並成一張表:

select * from student1 union select *from student2;

六、子查詢

有時候,查詢時需要的條件是另外一個select語句的結果,就會使用到子查詢。

1.帶IN關鍵字的子查詢

SQL語句:select * from student where Num IN(select Stu_id from score);

2.帶EXISTS關鍵字的子查詢

exists內查詢返回一個真價值,若返回true時,外查詢進行查詢,否則外查詢不進行查詢。

SQL語句:select * from student where exists(select * from score where C_name='計算機');

3.帶ANY關鍵字的子查詢

使用ANY關鍵字只要有一個滿足,就通過該條件來執行外查詢。

SQL語句:select sname,(date_format(from_days(now())-to_days(birthday)),'%Y')+0) as '年齡' from student where birthday>ANY(select birthday from student where bumen='計算機系');

4.帶ALL關鍵字的子查詢

使用ALL關鍵字必須滿足所有的內層查詢語句返回的所有結果,才執行外查詢

SQL語句:select sname,(date_format(from_days(now())-to_days(birthday)),'%Y')+0) as '年齡' from student where birthday>ALL(select birthday from student where bumen='計算機系');

 

暫時學了這么多內容,以后有更好的方式再來補充。


免責聲明!

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



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