对在所有部门工作的员工的查询是什么?这里的部门和员工有很多基数。
这些表是:
CREATE TABLE employees
(
employee_id int NOT NULL CONSTRAINT pk_employees PRIMARY KEY,
employee_name nvarchar(128) NOT NULL CONSTRAINT uk_employees_employee_name UNIQUE
);
CREATE TABLE departments
(
department_id int NOT NULL PRIMARY KEY,
department_name nvarchar(128) NOT NULL CONSTRAINT uk_departments_department_name UNIQUE
);
CREATE TABLE department_employees
(
department_id int NOT NULL CONSTRAINT fk_department_employees_departments REFERENCES departments(department_id),
employee_id int NOT NULL CONSTRAINT fk_departement_employees_employees REFERENCES employees(employee_id),
CONSTRAINT pk_deparment_employees PRIMARY KEY (department_id, employee_id)
)
样本数据:
INSERT INTO employees
VALUES (1, 'John Doe'), (2, 'Jane Doe'), (3, 'William Doe'), (4, 'Margaret Doe')
INSERT INTO departments
VALUES (1, 'Accounting'), (2, 'Humman Resources'), (3, 'Marketing')
INSERT INTO department_employees
VALUES
(1, 1), (2, 1), (3, 1),
(2, 2), (2, 3),
(3, 3), (3, 4)
预期结果:
+-------------+---------------+
| employee_id | employee_name |
+-------------+---------------+
| 1 | John Doe |
+-------------+---------------+
答案 0 :(得分:0)
在关系代数上此操作称为Relation Division:。
可以使用以下查询在sql中实现
SELECT *
FROM dbo.employees e
WHERE
NOT EXISTS (
SELECT *
FROM departments d
WHERE d.department_id NOT IN (
SELECT dp.department_id
FROM department_employees dp
WHERE dp.department_id = d.department_id AND dp.employee_id = e.employee_id
)
)
请注意,查询“给我所有部门的员工”等同于“给所有雇员没有该员工不在的部门”
答案 1 :(得分:0)
您可以在下面的查询中尝试使用此方法。
在一个变量中,所有不同的计数部门均已从部门主表中获取。之后,仅选择那些计数与关联表中不同的链接部门计数匹配的员工。
declare @distinctDeptCount int
SET @DistinctDeptCount = (SELECT Count(Distinct department_id) FROM departments)
--SELECT @DistinctDeptCount
SELECT Distinct employees.employee_id, employee_name
from employees
where employees.employee_id in (
select employee_id from department_employees GROUP BY employee_id HAVING COUNT(department_id) = @distinctDeptCount
)
OR
SELECT Distinct employees.employee_id, employee_name
from employees
where employees.employee_id in (
select employee_id from department_employees GROUP BY employee_id HAVING COUNT(department_id) =
(SELECT Count(Distinct department_id) FROM departments)
)
输出如下所示
employee_id employee_name
1 John Doe
答案 2 :(得分:-1)
您可以尝试
SELECT
emp.name
FROM
Employee emp
JOIN
EmpDept empd
ON
emp.EmployeeID = empd.EmpId
GROUP BY
emp.EmployeeID
HAVING
count(emp.EmployeeID) = (select count(1) from Department)