SQL語句的多表查詢方式(總結)

例如:按照 department_id 查詢 employees(員工表)departments(部門表)的信息。
sql

方式一(通用型):SELECT ... FROM ... WHERE
spa

SELECT e.last_name,e.department_id,d.department_name
FROM employees e,departments d
where e.department_id = d.department_id 

方式二:SELECT ... FROM ... NATURAL JOIN ...有侷限性:會自動鏈接兩個表中相同的列(可能有多個:department_id manager_id)
code

SELECT last_name,department_id,department_name
FROM employees
NATURAL JOIN departments 

方式三:SELECT ... JOIN ... USING ...有侷限性:好於方式二,但若多表的鏈接列列名不一樣,此法不合適 ast

SELECT last_name,department_id,department_name
FROM employees
JOIN departments
USING(department_id) 

方式四:SELECT ... FROM ... JOIN ... ON ...經常使用方式,較方式一,更易實現外聯接(左、右、滿class

SELECT last_name,e.department_id,department_name
FROM employees e
JOIN departments d
ON e.department_id = d.department_id 
相關文章
相關標籤/搜索