目錄
一、連接查詢
當查詢結果的列來源於多張表時,需要將多張表連接成一個大額數據表,再選擇合適的列返回
內連接:查詢的結果爲兩個表匹配到的數據
左連接:查詢的結果爲兩張表匹配到的數據加左表特有的數據,對於右表中不存在的數據用null填充
- 右連接:查詢的結果爲兩張表匹配到的數據加右表特有的數據,對於左表中不存在的數據用null填充
-- 三表連接 A B C -- 原理 1. A表和B表 兩表連接,產生結果AB(看做一張表) 2. AB和C表連接, 產生結果ABC。 -- 三表連接 students scores courses -- 練習 select * from students st inner join scores sc on st.studentno=sc.studentno inner join courses co on co.courseNo=sc.courseNo;
1 內連接
select * from 表1
inner join 表2 on 表1.列=表2.列
內連接的另外一種語法:
select * from 列1,列2 where 表1.列=表2.列
2 左連接
select * from 表1
left join 表2 on 表1.列=表2.列
3 右連接
select * from 表1
right join 表2 on 表1.列=表2.列
二、子查詢
在一個select語句中,嵌入另外一個select語句,那麼,嵌入的select語句稱之爲子查詢語句,外層的select稱之爲主查詢語句
主查詢和子查詢的關係:
- 子查詢是嵌入到主查詢中
- 子查詢是輔助主查詢的,要麼充當條件,要麼充當數據源
- 子查詢是可以獨立存在的語句,是一條完整的select語句
子查詢結果:
a. 標量子查詢:具體某個值(一行一列)
b. 列子查詢:一列數據(一列多行)
select * from scores where studentNo in (select studentNo from students where age=18)
c. 行子查詢:一行(一行多列)
select * from students where (class,age)=(select class,age from students where name = ‘王昭君’)
d. 表級子查詢:多行多列(相當於一個表)
select * from scores s
inner join (select * from courses where name in (‘數據庫','系統測試')) c
on s.courseNo = c.courseNo
子查詢中特定關鍵字作用:
- in
主查詢 where 列 in (列子查詢)
- any|some 任意一個
主查詢 where 條件 列 = any (列子查詢)
在條件查詢的結果中匹配任意一個即可,等價於in
- all
主查詢 where 列 = all(列子查詢):等於裏面所有
主查詢 where 列 <>all(列子查詢):不等於其中所有