MySQL多表查詢 三表查詢 鏈接查詢的套路

多表查詢 * 當咱們的一條記錄 分散不一樣的表中時,就須要進行多表查詢 例如 一對一 一對多 多對多mysql

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老師教過哪些人?


三表聯查sql

create table stu(id int primary key auto_increment,name char(10));spa

create table tea(id int primary key auto_increment,name char(10));code

 

create table tsr(id int primary key auto_increment,t_id int,s_id int,rem

foreign key(s_id) references stu(id),io

foreign key(t_id) references tea(id));table

insert into stu values(null,"張三"),(null,"李四");class

insert into tea values(null,"egon"),(null,"wer");select

insert into tsr values(null,1,1),(null,1,2),(null,2,2);nio

 


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";
相關文章
相關標籤/搜索