MySQL中的表连接是指将两个或多个表的行结合起来,基于两个表中的共同字段。MySQL支持多种表连接方式,以下是七种常见的连接方式:
- 内连接(INNER JOIN)
- 左外连接(LEFT JOIN / LEFT OUTER JOIN)
- 右外连接(RIGHT JOIN / RIGHT OUTER JOIN)
- 全外连接(FULL JOIN / FULL OUTER JOIN)
- 交叉连接(CROSS JOIN)
- 自然连接(NATURAL JOIN)
- 反连接(LEFT JOIN / RIGHT JOIN 使用 WHERE ... IS NULL)
练习SQL:
-- 创建表
CREATE TABLE employees (
employee_id INT,
name VARCHAR(50),
department_id INT
);
CREATE TABLE departments (
department_id INT,
department_name VARCHAR(50)
);
-- 插入数据
INSERT INTO employees (employee_id, name, department_id) VALUES (1, 'Alice', 10), (2, 'Bob', 20), (3, 'Charlie', 30);
INSERT INTO departments (department_id, department_name) VALUES (10, 'HR'), (20, 'IT'), (30, 'Sales');
-- 练习SQL
-- 1. 内连接
SELECT e.name, d.department_name
FROM employees e
INNER JOIN departments d ON e.department_id = d.department_id;
-- 2. 左外连接
SELECT e.name, d.department_name
FROM employees e
LEFT JOIN departments d ON e.department_id = d.department_id;
-- 3. 右外连接
SELECT e.name, d.department_name
FROM employees e
RIGHT JOIN departments d ON e.department_id = d.department_id;
-- 4. 全外连接
-- MySQL不直接支持FULL OUTER JOIN,但可以通过UNION来实现
SELECT e.name, d.department_name
FROM employees e
LEFT JOIN departments d ON e.department_id = d.department_id
UNION
SELECT e.name, d.department_name
FROM employees e
RIGHT JOIN departments d ON e.department_id = d.department_id;
-- 5. 交叉连接
SELECT e.name, d.department_name
FROM employees e
CROSS JOIN departments d;
-- 6. 自然连接
SELECT e.name, d.department_name
FROM employees e
NATURAL JOIN departments d;
-- 7. 反连接
-- 查找哪些员工不在部门表中
SELECT e.name
FROM employees e
LEFT JOIN departments d ON e.department_id = d.department_id
WHERE d.department_id IS NULL;
注意:MySQL不支持标准的FULL OUTER JOIN,但可以通过UNION来模拟。此外,自然连接(NATURAL JOIN)在实际使用中较少,因为它隐式地按照相同名称的字段进行等值连接,可能导致不可预期的结果,因此更多时候我们会明确指定连接条件。