如何在mySQL中选择异常

时间:2013-05-14 04:29:48

标签: mysql

SELECT部门FROM myTable WHERE联系人IS NULL

   Department    Contact
    ------------- ---------
    Cleaning      Jack
    Admin         Peter
    Software      James
    Cleaning      (null)
    Cleaning      Jill
    Hardware      (null)

在上表中,我如何选择联系人为空的部门,不包括现有联系人。

上述声明 将返回“清洁”和“硬件”。

我的预期只是“硬件”

如何只选择“硬件”或是否可以。

TIA

3 个答案:

答案 0 :(得分:2)

我认为您只想返回没有任何非空联系人的行。

SELECT
    DISTINCT department
FROM
    myTable
WHERE
    contact IS NULL
    AND department NOT IN (SELECT department FROM myTable where contact IS NOT NULL)

或者,如果你想在没有IN子句的情况下这样做:

SELECT
    DISTINCT a.[department]
FROM
    myTable AS a
LEFT OUTER JOIN
    myTable AS b
        ON b.[department] = a.[department]
        AND b.[contact] IS NOT NULL
WHERE
    a.[contact] IS NULL
    AND b.[contact] IS NULL

使用NOT NULL自我加入条件,然后通过检查JOIN子句中的NULL来验证WHERE失败。

答案 1 :(得分:1)

听起来您想在任何记录中排除与非空值相关联的部门。为此,您应该执行子查询以获取所有非空部门,并将其从检索空部门的查询中排除。像这样:

SELECT DISTINCT department
FROM mytable
WHERE contact is null 
AND department NOT IN (SELECT department FROM mytable where contact is not null)

答案 2 :(得分:0)

SELECT department,
         SUM(CASE WHEN Contact is not null THEN 1 ELSE 0 END) as count
         from myTable
         group by department
         HAVING count > 0 ;