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

时间:2015-09-17 10:43:55

标签: sql brackets multiple-conditions

[GET] /user/games

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

示例:

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

2 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:1)

您需要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'

然后这更合适并返回您的预期结果:

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

Demo