我有两张表departments
和employees
。
department
表具有主键department_id
。 employees
表具有外键department_id
。我想打印所有有员工的部门。
我尝试过使用语法,但这并不好。
SELECT
departments.department_id, employees.department_id
FROM
departments, employees
WHERE
departments.department_id <> employees.department_id;
答案 0 :(得分:2)
“我想打印所有有员工的部门”
-- I want to print all departments
SELECT *
FROM departments d
WHERE EXISTS (
-- that have employees
SELECT *
FROM employees e
WHERE e.department_id = d.department_id
);
答案 1 :(得分:1)
简单的解决方案:
select * from departments
where department_id in (select department_id from employees)
答案 2 :(得分:0)
您需要Employees表中引用的所有部门。 因此,您需要查看其department_id不为null的每个员工记录。然后你有一个与员工有关的部门。
SELECT
d.department_id,
d.department_name
FROM
departments d
JOIN employees e ON e.department_id = d.department_id
WHERE e.department_id IS NOT NULL
GROUP BY d.department_id
答案 3 :(得分:0)
SELECT
DISTINCT d.department_id
FROM
departments d
JOIN employees e ON e.department_id = d.department_id