多表查詢 * 當我們的一條記錄 分散不同的表中時,就需要進行多表查詢 例如 一對一 一對多 多對多
1.笛卡爾積查詢 意思是將兩個表中的所有數據 全部關聯在一起
例如 a表 有2條 b表有3條 一共6條
會產生大量的錯誤數據 需要用添加來過濾
select *from 表1,表2,....... where 過濾條件
連接查詢
內連接查詢 inner jon
select *from 表1 join 表2 on 關系過濾條件
兩邊的數據必須完全匹配成功才顯示
select *from emp join dept on dept.id = emp.dept_id;
外連接查詢 不常用(不應該出現這種沒有正確關聯的數據)
左外連接 left join
左邊表的數據無論是否匹配成功 都要全部顯示
select *from emp left join dept on dept.id = emp.dept_id;
右外連接 right join
右邊表的數據無論是否匹配成功 都要全部顯示
select *from emp right join dept on dept.id = emp.dept_id;
全外連接
mysql不支持 可以用合並查詢union來 將 左外連接和右外連接合並
select *from emp left join dept on dept.id = emp.dept_id
union
select *from emp right join dept on dept.id = emp.dept_id;
on 專門用於篩選出正確的匹配關系 只能與join一起使用
但是在join 中 可以把on 換成where
反過來 在普通查詢中不可以使用on
通常在連接查詢 join中推薦使用on
連接查詢解決問題的思路
1.先聯合查詢 select *from emp join dept
2.on 來篩選正確關系 on dept.id = emp.dept_id
3. where 來進行額外的條件過濾 where dept.id = 1
select *from emp join dept on dept.id = emp.dept_id where dept.id = 1;
多對多關系的案例:
egon老師教過哪些人?
三表聯查
create table stu(id int primary key auto_increment,name char(10));
create table tea(id int primary key auto_increment,name char(10));
create table tsr(id int primary key auto_increment,t_id int,s_id int,
foreign key(s_id) references stu(id),
insert into stu values(null,"張三"),(null,"李四");
insert into tea values(null,"egon"),(null,"wer");
insert into tsr values(null,1,1),(null,1,2),(null,2,2);
select tea.name,stu.name from tea join tsr join stu
on tea.id = tsr.t_id and stu.id = tsr.s_id
where tea.name = "egon";