常用sql操作总结_尚硅谷_宋红康
发布时间:2021-06-06
发布时间:2021-06-06
SQL语句的多表查询方式
例如:按照department_id查询employees(员工表)和departments(部门表) 的信息。
方式一(通用型):SELECT ... FROM ... WHERE
SELECT st_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)
SELECT last_name,department_id,department_name
FROM employees
NATURAL JOIN departments
方式三:SELECT ... JOIN ... USING ...
有局限性:好于方式二,但若多表的连接列列名不同,此法不合适 SELECT last_name,department_id,department_name
FROM employees
JOIN departments
USING(department_id)
方式四:SELECT ... FROM ... JOIN ... ON ...
常用方式,较方式一,更易实现外联接(左、右、满)
SELECT last_name,e.department_id,department_name
FROM employees e
JOIN departments d
ON e.department_id = d.department_id
--内连接
1)
--等值连接
--不等值连接
2)
--非自连接
--自连接
--外连接
--左外连接、右外连接、满外连接