数据库
首页 > 数据库> > 【MySQL】多表查询:内连接VS外连接

【MySQL】多表查询:内连接VS外连接

作者:互联网

区别:内连接只取两张表中满足where条件的部分(交集部分),外连接除了取满足的部分还会取不满足的部分。因此外连接又可以分为:左外连接、右外连接、全外连接。
image

1.内连接

SQL92内连接

SELECT employee_id,department_name
FROM employees e,departments d
WHERE e.`department_id` = d.department_id; 

SQL99内连接,使用join或inner join都一样

SELECT last_name,department_name
FROM employees e 
INNER JOIN departments d ON e.`department_id` = d.`department_id`;

SELECT last_name,department_name,city
FROM employees e 
JOIN departments d ON e.`department_id` = d.`department_id`
JOIN locations l ON d.`location_id` = l.`location_id`;

2.外连接

查询所有的员工的last_name,department_name信息,有员工没有部门,有的部门为空。

#这种方式只能查出106条数据,错误的
SELECT employee_id,department_name
FROM employees e,departments d
WHERE e.`department_id` = d.department_id;   # 需要使用左外连接

SQL92版本实现外连接,MySQL不支持SQL92语法中外连接的写法,Oracle支持,在缺少的那个表后使用+,查出107条数据,有一个员工没有部门

SELECT employee_id,department_name
FROM employees e,departments d
WHERE e.`department_id` = d.department_id(+);

SQL99版本实现外连接
查询所有的员工的last_name,department_name信息。

# 左外连接:
SELECT last_name,department_name
FROM employees e LEFT JOIN departments d
ON e.`department_id` = d.`department_id`;

#右外连接:
SELECT last_name,department_name
FROM employees e RIGHT OUTER JOIN departments d
ON e.`department_id` = d.`department_id`;


#满外连接:mysql不支持FULL OUTER JOIN
SELECT last_name,department_name
FROM employees e FULL OUTER JOIN departments d
ON e.`department_id` = d.`department_id`;

标签:多表,name,departments,id,VS,department,连接,SELECT
来源: https://www.cnblogs.com/zhishu/p/16596449.html