MySQL之連接查詢



幾種連接

  1. 內鏈接 (inner) 兩張表公共的部分集合在一起(取交集),產生的結果集

  2. 全外連接 (full outer) 所有在A表和B表中存在的數據。無法對應Null填充 只存在於A表或B表中的數據,過濾兩個表公共的部分

  1. 左外連接 (left outer) A表和B表,以左表爲基礎, 只存在A表且不存在B表中的結果
  1. 右外連接 (right outer) 以右表爲基礎,(保留B的數據)
  1. 交叉連接 (cross) 如果A和B是兩個集合,交叉連接就是AxB

連接查詢

對有關係的多張表進行查詢,使用連接join

區別:結果集不一樣

select students.name,subjects.title,scores.score 
from scores 
inner join students on scores.stuid=students.id 
inner join subjects on scores.subid=subjects.id;
查詢男生的姓名/總分

建立連接: students.id=sccores.stuid

使用sum-->分組, 姓名:每個人的總分

select name,sum(score) from students 
inner join scores on 
students.id=scores.stuid 
where students.gender=1
group by students.name;
查詢科目的名稱/ 平均分
select subjects.title,avg(scores.score) from scores  
inner join subjects on 
scores.subid=subjects.id
group by subjects.title;
查詢未刪除科目的名稱/最高分/平均分
select title,max(scores.score),avg(scores.score) from subjects 
inner join scores on 
subjects.id=scores.subid 
where subjects.isDelete=0 
group by subjects.title;

發佈了86 篇原創文章 · 獲贊 33 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章