SQL计数与SELECT子句中的另一个表

时间:2014-04-24 09:56:18

标签: mysql sql sql-server oracle

在我的数据库中,有2个不同的字段

我。)员工 ii。)部门

在我的employee表中,

NAME      Department
---------------------
John          IT
Siti       Research
Jason      Research

在我的Department

Name
------------
IT
Research
Computer

使用声明

SELECT DEPARTMENT.DNAME
FROM DEPARTMENT,
     EMPLOYEE
WHERE DEPARTMENT.DNAME = EMPLOYEE.DNAME
  AND
    (SELECT COUNT(*)
     FROM EMPLOYEE.DNAME)=0;

department中没有员工显示

Name
--------------
Computer

继续尝试,但有一些错误

4 个答案:

答案 0 :(得分:4)

两种选择:

  1. 使用IN

    SELECT name FROM Department
    WHERE name NOT IN (SELECT DISTINCT Department 
                       FROM Employee)
    
  2. 使用Left Join

    SELECT D.NAME 
    FROM DEPARTMENT D LEFT JOIN EMPLOYEE ON D.NAME = EMPLOYEE.Department
    WHERE EMPLOYEE.Department IS NULL
    

    Fiddle中的示例。

    如果您的表中有数千条记录,此方法将显示出比其他方法更高的性能。

答案 1 :(得分:2)

试试NOT IN。子查询需要DISTINCT以避免将来出现性能问题:

SELECT name FROM Department
WHERE name NOT IN ( SELECT DISTINCT Department FROM Employee);

NOT EXIST,在大多数情况下更快:

SELECT name FROM Department
WHERE NOT EXIST  ( SELECT 1 FROM Employee 
                   WHERE Employee.Department = Department.name);

答案 2 :(得分:1)

您没有说明您的错误,但您可以选择未显示在员工表中的所有部门:

SELECT DEPARTMENT.DNAME 
FROM DEPARTMENT 
WHERE DEPARTMENT.DNAME NOT IN (SELECT DEPARTMENT FROM EMPLOYEE);

答案 3 :(得分:1)

SELECT D.Name
FROM Employee E
RIGHT JOIN Department D
ON E.Department=D.Name
WHERE E.Department IS NULL

SQL Fiddle DEMO