查询出公司员工的 last_name,department_name, city(三 表关联查询,用两种方法来写)
时间: 2024-10-19 12:02:28 浏览: 26
查询公司员工的姓氏(last_name)、部门名(department_name)以及所在城市(city),通常需要从三个相关的表(假设分别为 employees, departments 和 cities)进行联接。这里有两种常见的 SQL 方法来实现这种关联查询:
**方法一:INNER JOIN (内连接)**
```sql
SELECT e.last_name, d.department_name, c.city
FROM employees AS e
INNER JOIN departments AS d ON e.department_id = d.department_id
INNER JOIN cities AS c ON d.city_id = c.city_id;
```
在这个查询中,我们首先通过 `employees` 表和 `departments` 表的 `department_id` 进行匹配,然后通过 `departments` 表和 `cities` 表的 `city_id` 进行匹配。
**方法二:DEPARTMENT_ID IN (子查询) 或 EXISTS (嵌套查询) **
```sql
-- 方法一:使用子查询
SELECT e.last_name, d.department_name, c.city
FROM employees AS e
WHERE e.department_id IN (
SELECT department_id FROM departments WHERE city_id IN (SELECT city_id FROM cities)
);
-- 方法二:使用 EXISTS
SELECT e.last_name, d.department_name, c.city
FROM employees AS e
JOIN departments AS d ON e.department_id = d.department_id
JOIN cities AS c ON d.city_id = c.city_id
WHERE EXISTS (SELECT * FROM cities WHERE cities.city_id = d.city_id);
```
在这两种方法中,都会返回那些在所有相关表中有对应记录的员工的姓氏、部门名称和城市信息。
阅读全文