多表查詢
在多個表中查詢需要的數據
例如:有班級表 和學生表
給你已給班級名稱 請查詢所有的學員數據
先查班級表 得到一個班級的id 再根據id去學院表查詢對應的學員
准備數據:
create table emp (id int,name char(10),sex char,dept_id int);
insert emp values(1,"大黃","m",1);
insert emp values(2,"老王","m",2);
insert emp values(3,"老李","w",30);
create table dept (id int,name char(10));
insert dept values(1,"市場");
insert dept values(2,"財務");
insert dept values(3,"行政");
多表查詢的方式
1.笛卡爾積查詢
什么是笛卡爾積,用坐標中的一條記錄 去鏈接另一張表的所有記錄
就像是把 兩張表的數據做了一個乘法
這將導致 產生大量的無用重復數據
我們要的效果是:員工表中的部門id 與 部門表中的id相同 就拼接在一起
用 where 篩選出正確的數據
select *from emp,dept where emp.dept_id = dept.id;
on關鍵字
作用 用於多表查詢是 進行條件限制
select *from emp,dept on emp.dept_id = dept.id; 這是錯誤的語法 因為 on 它只能用在專門多表查詢語句中
2.內連接查詢
inner join
select *from emp inner join dept on emp.dept_id = dept.id;
# 查詢 所有的員工以及他們所屬的部門信息
3.左外連接
left join
左邊表中的數據完全顯示 右邊表中的數據匹配上才顯示
select *from emp left join dept on emp.dept_id = dept.id;
# 查詢 所有的部門以及他們所有的員工信息
4.右外連接
right join
左邊表中的數據匹配上才顯示 右邊表中的數據完全顯示
select *from emp right join dept on emp.dept_id = dept.id;
# 在一個表中 顯示多個表中的所有數據
5. 全外鏈接
full join mysql不支持 oracle支持
可以通過union 間接實現
union 表示合並查詢 意思是把多個查詢結果合並在一起顯示
要求是 被合並的表結構必須相同
默認去除重復
合並但是不去除重復
union all
select *from emp right join dept on emp.dept_id = dept.id
union
select *from emp left join dept on emp.dept_id = dept.id;
總結:多表鏈接 在書寫時 按照填空來書寫 如果左邊要全部顯示 用left join
右邊全部顯示 用right join
全部顯示 把左鏈接的結果和右鏈接的結果 合並
當然 也可以更多表一起查 但是 沒有意義 並且你要盡量避免 太多表 一起查
最多三張 在多對多的時候
select *from emp left join dept left join xxtable on emp.dept_id = dept.id;
create table tec(id int,name char(10));
insert into tec value(1,"egon");
insert into tec value(2,"yyh");
create table stu(id int,name char(10));
insert into stu value(1,"大傻");
insert into stu value(2,"中傻");
insert into stu value(3,"小傻");
create table s_t(s_id int,t_id int);
insert into s_t value(1,2);
insert into s_t value(2,2);
insert into s_t value(3,1);
需求 找出 yyh 這個老師 教過的學生信息
思路:
第一步 到關系表中 去查詢 哪些老師教過哪些學生(學生的id) 形成了一個臨時表
第二步 將上一步得到臨時表 與 學生表進行連接
第三步 加上額外的篩選條件 老師的name 是 yyh
select tec.name teacher,stu.name student from
tec inner join s_t on tec.id = s_t.t_id
inner join stu on s_t.s_id = stu.id
where tec.name = "egon" ;
子查詢
什么是子查詢:將上一次查詢的結果 作為本次查詢的原始數據(或是查詢條件)
也就是嵌套查詢 這中嵌套的語法一班不讓寫,不允許使用,