SQL多表連線實戰

2021-10-09 19:30:57 字數 2503 閱讀 8711

操作符名稱

描述inner join

如果表中至少乙個匹配,則返回行

left join

即使右邊中沒有匹配,也從左表中返回所有的行

right join

即使左表中沒有匹配,也從右邊中返回所有的行

連線查詢

如需要多張資料表的資料進行查詢,則可通過連線運算子實現多個查詢

內連線 inner join

查詢兩個表中的結果集中的交集

外連線 outer join

左外連線 left join

(以左表作為基準,右邊表來一一匹配,匹配不上的,返回左表的記錄,右表以null填充)

右外連線 right join

(以右表作為基準,左邊表來一一匹配,匹配不上的,返回右表的記錄,左表以null填充)

等值連線和非等值連線

*/-- 查詢參加了考試的同學資訊(學號,學生姓名,科目編號,分數)

select * from student;

select * from result;

/*思路:

(1)分析需求,確定查詢的列**於兩個表,student result,連線查詢

(2)確定使用哪種連線查詢?(內連線)

*/select s.studentno,studentname,subjectno,studentresult

from student s

inner join result r

on r.studentno = s.studentno

-- 右連線(也可實現)

select s.studentno,studentname,subjectno,studentresult

from student s

right join result r

on r.studentno = s.studentno

-- 等值連線

select s.studentno,studentname,subjectno,studentresult

from student s , result r

where r.studentno = s.studentno

-- 左連線 (查詢了所有同學,不考試的也會查出來)

select s.studentno,studentname,subjectno,studentresult

from student s

left join result r

on r.studentno = s.studentno

-- 查一下缺考的同學(左連線應用場景)

select s.studentno,studentname,subjectno,studentresult

from student s

left join result r

on r.studentno = s.studentno

where studentresult is null

-- 思考題:查詢參加了考試的同學資訊(學號,學生姓名,科目名,分數)

select s.studentno,studentname,subjectname,studentresult

from student s

inner join result r

on r.studentno = s.studentno

inner join `subject` sub

on sub.subjectno = r.subjectno

-- 查詢學員及所屬的年級(學號,學生姓名,年級名)

select studentno as 學號,studentname as 學生姓名,gradename as 年級名稱

from student s

inner join grade g

on s.`gradeid` = g.`gradeid`

-- 查詢科目及所屬的年級(科目名稱,年級名稱)

select subjectname as 科目名稱,gradename as 年級名稱

from subject sub

inner join grade g

on sub.gradeid = g.gradeid

-- 查詢 資料庫結構-1 的所有考試結果(學號 學生姓名 科目名稱 成績)

select s.studentno,studentname,subjectname,studentresult

from student s

inner join result r

on r.studentno = s.studentno

inner join `subject` sub

on r.subjectno = sub.subjectno

where subjectname='資料庫結構-1'

SQL多表連線

oracle8 select a.b.from a,b where a.id b.id 相當於左聯接 select a.b.from a,b where a.id b.id 相當於右聯接 oracle9 支援以上的寫法,還增加了leftjoin right join等 select a.b.from...

SQL多表連線

1.內連線 查詢兩張表共有部分 等值連線 語法 select from 表a inner join 表b on a.key b.key 2.左連線 把左邊表的內容全部查出,右邊表只查出滿足條件的記錄 語法 select from 表a left join 表b on a.key b.key 3.右連...

SQL多表連線查詢

本文主要列舉兩張和三張表來講述多表連線查詢。新建兩張表 表1 student 截圖如下 表2 course 截圖如下 此時這樣建表只是為了演示連線sql語句,當然實際開發中我們不會這樣建表,實際開發中這兩個表會有自己不同的主鍵。一 外連線 外連線可分為 左連線 右連線 完全外連線。1 左連線 lef...