如果第二个条件为false,则SQL查询在一个条件上选择

时间:2014-11-25 10:26:10

标签: sql ms-access

我正在尝试向Access数据库提出SQL查询。这是一个示例表,有助于解释我遇到的问题:

ID     Status
-------------
123    Pass
123    Fail
456    Pass
789    Pass
789    Fail
012    Fail

我想提取所有IDStatus=Pass,但没有Status=Fail

因此,从上表中可以得出的唯一记录是:

456   Pass

3 个答案:

答案 0 :(得分:1)

SELECT DISTINCT ID, Status
FROM table
WHERE ID NOT IN (SELECT ID FROM table WHERE Status = 'Fail')
  AND Status = 'Pass'

小评论:AND Status = 'Pass'在这种情况下不是必需的,因为只有两个状态,如果第一个条件为真,第二个也是真的(tautology),但我决定离开它为了更好的指示。

It works.

答案 1 :(得分:0)

使用NOT EXISTS谓词:

SELECT  *
FROM tablename AS t1
WHERE t1.Status ='Pass'
AND NOT EXISTS (SELECT 1
               FROM Tablename AS t2
               WHERE t1.Id = t2.ID AND t2.status = 'Fail')

答案 2 :(得分:-1)

SELCT * FROM table WHERE status = 'Pass' AND
id NOT IN (SELECT id FROM table WHERE status ='Fail')