0

例如

id  departmentname
1     x
2     y
3     z

员工

fkdepartmentid empname
         1      john
         1      sam
         2      ram
         3      hari    

这里一个empname可以属于任意数量的departments。

我的要求是从department表中获取所有部门empname!=john(通过连接)。

我尝试了以下查询:

SELECT d.id FROM department d
 INNER JOIN employee e ON d.id=e.fkdepartmentid
  WHERE((e.empname<>'1')OR d.id IN (SELECT DISTINCT fkdepartmentid FROM employee WHERE fkdepartmentid NOT IN (SELECT DISTINCT fkdepartmentid FROM employee WHERE empname=sam)) ) GROUP BY d.id

但是,查询速度很慢,并且在某些情况下会失败。结果应该是 2 和 3。我怎样才能达到这些结果?

4

3 回答 3

0

如果理解正确,您想排除部门 1,因为 Jhon 是该部门的雇主。如果是这样,您需要反转条件。

尝试

SELECT * 
  FROM department
 WHERE id NOT IN
( 
  SELECT fkdepartmentid 
    FROM employee 
   WHERE empname = 'john' 
   GROUP BY fkdepartmentid
)

输出:

| 身份证 | 部门名称 |
----------------------
| 2 | 是 |
| 3 | z |

这是SQLFiddle演示

于 2013-06-13T09:35:03.150 回答
0
Here you go

SELECT * FROM department WHERE id IN( SELECT fkdepartmentid FROM employee WHERE empname !='john' GROUP BY fkdepartmentid )
于 2013-06-13T09:26:00.290 回答
0

这是不使用嵌套查询的一种:

SELECT t1.*
FROM department AS t1
LEFT JOIN employee AS t2
ON t2.deptid = t1.id AND t2.name IN ('john', 'rari')
WHERE t2.name IS NULL;

这列出了所有没有任何员工的部门在列表中。

于 2013-06-13T09:41:37.653 回答