SQL 括号中的两个条件都为真

SQL where both conditions in brackets are true

SELECT
    *
FROM 
    TableName
WHERE
    Column1 = 'X'
    AND Column2 = 'Y'
    AND (Column3 != 'D' AND Column4 != 'D') -- Want to apply this filter ONLY if both conditions are true

如何编写第三个过滤器,以便仅当它们都为真时才应用它。目前,括号没有区别,但我需要括号中的表达式被视为单个条件

示例:

Column1     Column2     Column3     Column4
X           Y           D           L   
X           Y           L           L   
X           Y           L           D   
X           Y           D           D   -- want to remove this line

结果应该是:

Column1     Column2     Column3     Column4
X           Y           D           L   
X           Y           L           L   
X           Y           L           D   

您需要 OR:

SELECT
    *
FROM 
    TableName
WHERE 
    (Column1 <> 'X' OR Column2 <> 'Y')
OR
    (Column1 = 'X' AND Column2 = 'Y' AND (Column3 != 'D' AND Column4 != 'D')) 

旁注:您的预期结果是错误的或您的条件。 This 是您的条件的结果。我猜你想要 Column3 != 'D' OR Column4 != 'D' 而不是 Column3 != 'D' AND Column4 != 'D'.

那么这更合适 returns 您的预期结果:

SELECT
    *
FROM 
    TableName
WHERE 
    (Column1 <> 'X' OR Column2 <> 'Y')
OR
    (Column1 = 'X' AND Column2 = 'Y' AND (Column3 != 'D' OR Column4 != 'D')) 

Demo

SELECT
    *
FROM 
    TableName
WHERE
    Column1 = 'X'
    AND Column2 = 'Y'
    AND NOT (Column3 = 'D' AND Column4 = 'D')