多表內連接查詢使用的語句是什么

mysql中,可以使用“inner join”語句進行多表內連接查詢,只需要使用“select * from 表 inner join 表 on 表1.字段=表2.字段;”語句即可。組合兩個表中的記錄,返回關聯字段相符的記錄。

多表內連接查詢使用的語句是什么

本教程操作環境:windows7系統、mysql8版本、Dell G3電腦。

內連接?

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;

擴展資料:

外連接

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;則盡量不使用此語句,產生的結果過于繁瑣。

交叉連接

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=’計算機系’);

相關學習推薦:mysql教程(視頻)

? 版權聲明
THE END
喜歡就支持一下吧
點贊6 分享