在 MySQL 中,内连接(INNER JOIN)、左连接(LEFT JOIN 或 LEFT OUTER JOIN)和右连接(RIGHT JOIN 或 RIGHT OUTER JOIN)是用于合并两个或多个表中的数据的不同类型的连接操作。以下是它们之间的区别:
内连接(INNER JOIN):
SELECT * FROM table1 INNER JOIN table2 ON table1.column = table2.column;
左连接(LEFT JOIN 或 LEFT OUTER JOIN):
SELECT * FROM table1 LEFT JOIN table2 ON table1.column = table2.column;
右连接(RIGHT JOIN 或 RIGHT OUTER JOIN):
SELECT * FROM table1 RIGHT JOIN table2 ON table1.column = table2.column;
下面是一个简单的示例,演示了内连接、左连接和右连接的用法:
示例数据:
-- 表1:employees
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(50),
department_id INT
);
-- 表2:departments
CREATE TABLE departments (
department_id INT PRIMARY KEY,
department_name VARCHAR(50)
);
-- 数据示例
INSERT INTO employees (emp_id, emp_name, department_id) VALUES (1, 'Alice', 101);
INSERT INTO employees (emp_id, emp_name, department_id) VALUES (2, 'Bob', 102);
INSERT INTO employees (emp_id, emp_name, department_id) VALUES (3, 'Charlie', 101);
INSERT INTO departments (department_id, department_name) VALUES (101, 'HR');
INSERT INTO departments (department_id, department_name) VALUES (102, 'IT');
内连接示例:
-- 内连接返回 employees 和 departments 中 department_id 匹配的行
SELECT employees.emp_id, employees.emp_name, departments.department_name
FROM employees
INNER JOIN departments ON employees.department_id = departments.department_id;
左连接示例:
-- 左连接返回所有 employees 行,以及与 departments 中 department_id 匹配的行
SELECT employees.emp_id, employees.emp_name, departments.department_name
FROM employees
LEFT JOIN departments ON employees.department_id = departments.department_id;
右连接示例:
-- 右连接返回所有 departments 行,以及与 employees 中 department_id 匹配的行
SELECT employees.emp_id, employees.emp_name, departments.department_name
FROM employees
RIGHT JOIN departments ON employees.department_id = departments.department_id;
在这个示例中,employees
表和 departments
表通过 department_id
列进行连接。不同类型的连接操作会返回不同的结果集,涉及到匹配行和 NULL 值的处理。