MySQL中多表查詢總結

在工作之後,數據庫運用最多的就是查詢了,多表查詢有三類,分別是:內連接查詢、外連接查詢、子查詢。下面我們一一介紹。

文章前提是:存在兩張表:employees(員工表),departments(部門表);其中員工表中有外鍵dept_id指向部門表的主鍵id.

一、內連接查詢

  • 寫內連接查詢前要考慮的問題
/*
1、從哪些表中查數據?
2、條件是什麼?
3、查詢哪些字段?
*/
  • 隱式內連接:使用where條件
-- 查詢員工的姓名,性別,生日以及部門
select employees.last_name,employees.gender,employees.birth_date,departments.dept_name
from employees,departments 
where employees.dept_id=departments.id;
  • 顯示內連接:
-- 語法:select 字段列表 from 表1 inner join 表2 on 條件
-- 示例:展示員工信息和部門信息
select * from employees 
inner join departments 
on 
employees.dept_id=departments.id limit 10

二、外連接查詢

  • 左外鏈接
-- 語法:select 字段列表 from 表1 left (outer) join 表2 on 條件
-- 說明:查詢的是左表所有數據以及其交集部分
  • 右外連接
-- 語法:select 字段列表 from 表1 right (outer) join 表2 on 條件
-- 說明:查詢的是右表所有數據以及其交集部分

三、子查詢

-- 概念:查詢中嵌套查詢,稱嵌套的查詢爲子查詢
-- 重要:
/*
(1)情況一:
子查詢的結果是單行單列的
子查詢可以作爲條件,使用運算符去判斷(>,<,>=,<=,=)

(2)情況二:
子查詢的結果是多行單列的
子查詢可以作爲條件,使用in來判斷

(3)情況三:
子查詢的結果是多行多列的
子查詢可以作爲一張虛擬表
*/
-- 示例情況一:查詢員工工資小於平均工資的人
select * from employees where employees.salary<(select avg(salary) from employees);
-- 示例情況二:查詢'財務部'和'市場部'所有員工信息
select * from employees where dept_id
in
(select id from departments where name='財務部' or name='市場部')
-- 示例情況三:查詢員工入職日期是2011-11-11日之後的員工信息和部門信息
select * from departments t1,
(select * from employees where employees.join_date>'2011-11-11')t2
where t1.id=t2.dept_id;

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章