mysql的三表查询的例子
时间: 2024-05-10 19:19:21 浏览: 47
多表查询案例
5星 · 资源好评率100%
三表查询是指在同一条SQL语句中查询三个或更多的表,并将它们连接起来。下面是一个MySQL的三表查询例子:
有三张表:
```
employees:
+----+-------+--------+----------+
| id | name | gender | hiredate |
+----+-------+--------+----------+
| 1 | Tom | M | 2015-07-01 |
| 2 | Jerry | F | 2016-09-12 |
| 3 | Bob | M | 2017-02-15 |
+----+-------+--------+----------+
departments:
+----+------------+
| id | name |
+----+------------+
| 1 | Sales |
| 2 | Marketing |
| 3 | HR |
+----+------------+
employee_departments:
+----+-------------+---------------+
| id | employee_id | department_id |
+----+-------------+---------------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 2 |
| 4 | 3 | 3 |
+----+-------------+---------------+
```
三表查询语句如下:
```
SELECT employees.name, departments.name
FROM employees
JOIN employee_departments ON employees.id = employee_departments.employee_id
JOIN departments ON employee_departments.department_id = departments.id;
```
查询结果如下:
```
+-------+-----------+
| name | name |
+-------+-----------+
| Tom | Sales |
| Tom | Marketing |
| Jerry | Marketing |
| Bob | HR |
+-------+-----------+
```
这个例子中,我们想要查询每个员工所在的部门。我们使用了 `JOIN` 来连接三张表,第一个 `JOIN` 连接了 employees 和 employee_departments 表,第二个 `JOIN` 连接了 employee_departments 和 departments 表。最终结果是返回了每个员工的名字和他们所在的部门。
阅读全文