我有以下问题:
查找在所有受其控制的项目中工作的员工的姓名
部门编号5。
我有的表是雇员(SSN),Works_On(SSN,PNumber),项目(PNumber,DNumber)。
我正在尝试找出“全部”部分。我尝试了不同的方法,但是我想做的是创建一个规范的查询树,因此我需要确保可以将SQL查询转换为该树。
我尝试了以下方法:
SELECT E.Fname, E.Lname
FROM Employee AS E, works_on AS W
WHERE E.SSN IN ALL
(
SELECT SSN
FROM Projects AS P
WHERE W.SSN = E.SSN AND W.PNUMBER = P.PNUMBER AND P.DNUMBER = 5
);
但是我不确定自从我使用
IN ALL
后它是否会起作用。我尝试做的另一件事是,对工作进行统计并按员工分组,然后对项目进行计数。最终我发现了这一点:
select fname, lname
from employee
where not exists ( (select pnumber from project where dnum = 5)
MINUS
(select pno from works_on where essn = ssn)
);
但是我无法将其转换为树。
您对我有什么建议吗?是的,这是家庭作业。
最佳答案
DROP TABLE IF EXISTS employees;
CREATE TABLE employees (employee_id SERIAL PRIMARY KEY);
DROP TABLE IF EXISTS employee_project;
CREATE TABLE employee_project (employee_id INT NOT NULL, project_id INT NOT NULL,PRIMARY KEY(employee_id,project_id));
DROP TABLE IF EXISTS projects;
CREATE TABLE projects(project_id SERIAL PRIMARY KEY, department_id INT NOT NULL);
INSERT INTO employees VALUES (101),(102),(103);
INSERT INTO employee_project VALUES (101,5004),(101,5005),(101,5006),(101,5007),(102,5004),(102,5007),(102,5008),(103,5006),(103,5007),(103,5008);
INSERT INTO projects VALUES (5004,1),(5005,2),(5006,5),(5007,5),(5008,4),(5009,3);
Consider the following:
SELECT *
FROM employees e
JOIN projects p
LEFT
JOIN employee_project ep
ON ep.employee_id = e.employee_id
AND ep.project_id = p.project_id
WHERE p.department_id = 5;
+-------------+------------+---------------+-------------+------------+
| employee_id | project_id | department_id | employee_id | project_id |
+-------------+------------+---------------+-------------+------------+
| 101 | 5006 | 5 | 101 | 5006 |
| 102 | 5006 | 5 | NULL | NULL |
| 103 | 5006 | 5 | 103 | 5006 |
| 101 | 5007 | 5 | 101 | 5007 |
| 102 | 5007 | 5 | 102 | 5007 |
| 103 | 5007 | 5 | 103 | 5007 |
+-------------+------------+---------------+-------------+------------+
从此结果,我们可以得出两个结论,这两个事实都可以证明对解决问题有帮助。
结果中不同项目的数量等于与用户101和103一起列出的不同项目的数量(即,这些数字出现在第4列中的次数)。
用户102的结果为空,这意味着他们并未参与该部门的所有项目。
关于mysql - 从特定范围选择全部,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50160205/