拥有员工的SQL Print部门

时间:2015-03-22 12:03:22

标签: sql oracle oracle11g

我有两张表departmentsemployees

department表具有主键department_idemployees表具有外键department_id。我想打印所有有员工的部门。

enter image description here

我尝试过使用语法,但这并不好。

SELECT 
    departments.department_id, employees.department_id 
FROM 
    departments, employees
WHERE 
    departments.department_id <> employees.department_id;

4 个答案:

答案 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