SQL Join无效(零记录返回)?

时间:2016-08-08 08:58:13

标签: sql

我在教程中找到了这个问题,

Emp( eid: integer, ename: string, age: integer, salary: real)
Works( eid: integer, did: string, pct-time: integer)
Dept( did: string, budget: real, managerid: integer)

作为那个问题,员工可以在很多部门工作。用于映射员工和部门的工作表。 Works关系的pct_time字段显示给定员工在给定部门中工作的时间百分比。

然后要求打印在硬件和软件部门工作的每位员工的姓名和年龄。

为此,我写了以下SQL,但它没有用?有谁可以解释这个问题。

SELECT Emp.ename, Emp.age
FROM Emp
JOIN Works ON Works.eid = Emp.eid
WHERE Works.did = 'Hardware' AND Works.did = 'Software'

3 个答案:

答案 0 :(得分:1)

在单个记录中,Works.did不能同时为硬件和软件。因此,您需要对数据进行分组,对您要查找的Works.did进行过滤,然后仅采用两者 Works.did

的群组
SELECT Emp.ename, Emp.age
FROM Emp
JOIN Works ON Works.eid = Emp.eid
WHERE Works.did IN ('Hardware', 'Software')
GROUP BY Emp.ename, Emp.age
HAVING count(Works.did) = 2

答案 1 :(得分:1)

希望有所帮助:

SELECT Emp.ename, Emp.age
FROM Emp
INNER JOIN Works AS W1 ON W1.eid = Emp.eid
INNER JOIN Works AS W2 ON W2.eid = Emp.eid
WHERE W1.did = 'Hardware' 
AND W2.did = 'Software'

答案 2 :(得分:0)

试试这个

SELECT Emp.ename, Emp.age
FROM Emp
JOIN Works ON Works.eid = Emp.eid
WHERE Works.did IN ('Hardware', 'Software')
GROUP BY 1,2
HAVING count(distinct Works.did) = 2