0

简化问题:

如果我有以下内容(其中 CN = 名称,UID = emp.ID,supervisor = emp.id 的主管):

CN          UID      supervisor  
Jerry       4         NULL
Dave        11        15    
Dan         12        16    
Jack        13        17    
Jason       14        11    
Tom         10        15    
Berry       16        12

我希望 Dave 和 Dan 都不在名单上,因为他们也是主管(第二名或更高)。

    SELECT
reports_accreditallfr.cn,
reports_accreditallfr.uid,
reports_accreditallfr.supervisor
FROM
reports_accreditallfr
WHERE
reports_accreditallfr.uid NOT IN ( reports_accreditallfr.supervisor)

我目前的陈述说明了一切。我猜我的 NOT IN 语句只是逐行工作,而不是扫描整个主管列。

4

3 回答 3

1

你需要一个子查询。

SELECT reports_accreditallfr.cn, reports_accreditallfr.uid,
       reports_accreditallfr.supervisor
FROM reports_accreditallfr
WHERE reports_accreditallfr.uid NOT IN (select reports_accreditallfr.supervisor
                                        from reports_accreditallfr
                                        where reports_accreditallfr.supervisor is not null
                                       );

你的表达相当于:

reports_accreditallfr.uid <> reports_accreditallfr.supervisor

这可能在所有行上都是正确的。

于 2013-09-11T20:30:20.493 回答
1

如果要省略在uid列中出现的列中具有值的supervisor行(对于表中的至少一行),并且如果uid保证是唯一的,

你可以使用“反加入”模式来获得它:

SELECT r.cn
     , r.uid
     , r.supervisor
  FROM reports_accreditallfr r
  LEFT
  JOIN reports_accreditallfr s
    ON s.supervisor = r.uid
 WHERE s.supervisor IS NULL

注意: LEFT JOIN 操作返回来自 的所有行r,该WHERE子句忽略返回的任何行中至少有一个匹配行s

与所选答案中的查询相比,此查询略有不同。此查询将返回在 中具有 NULL 值的行uid,而所选答案中的查询将省略这些行(因为谓词NULL NOT IN (foo)不会返回“true”。

可以修改所选答案中的查询以包含OR uid IS NULL与该查询匹配的谓词;--或者-- 可以更改此查询以包含AND r.uid IS NOT NULL谓词,以使结果集匹配。

(我们没有任何 uid 值为 NULL 的行的示例;但只是在更一般的情况下需要注意的事情。)

于 2013-09-11T23:00:13.517 回答
0

尝试使用SELECT声明NOT IN

SELECT
    reports_accreditallfr.cn,
    reports_accreditallfr.uid,
    reports_accreditallfr.supervisor
FROM
    reports_accreditallfr
WHERE
    reports_accreditallfr.uid NOT IN (SELECT reports_accreditallfr.supervisor FROM reports_accreditallfr) 

您还可以将您的陈述简化为以下内容:

SELECT
    cn,
    uid,
    supervisor
FROM
    reports_accreditallfr
WHERE
    uid NOT IN (SELECT supervisor FROM reports_accreditallfr) 
于 2013-09-11T20:30:53.140 回答