SQL Logic Operator Precedence: And and Or

后端 未结 4 668
深忆病人
深忆病人 2020-11-21 23:53

Are the two statements below equivalent?

SELECT [...]
FROM [...]
WHERE some_col in (1,2,3,4,5) AND some_other_expr

and

SELE         


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-22 00:29

    Query to show a 3-variable boolean expression truth table :

    ;WITH cteData AS
    (SELECT 0 AS A, 0 AS B, 0 AS C
    UNION ALL SELECT 0,0,1
    UNION ALL SELECT 0,1,0
    UNION ALL SELECT 0,1,1
    UNION ALL SELECT 1,0,0
    UNION ALL SELECT 1,0,1
    UNION ALL SELECT 1,1,0
    UNION ALL SELECT 1,1,1
    )
    SELECT cteData.*,
        CASE WHEN
    
    (A=1) OR (B=1) AND (C=1)
    
        THEN 'True' ELSE 'False' END AS Result
    FROM cteData
    

    Results for (A=1) OR (B=1) AND (C=1) :

    A   B   C   Result
    0   0   0   False
    0   0   1   False
    0   1   0   False
    0   1   1   True
    1   0   0   True
    1   0   1   True
    1   1   0   True
    1   1   1   True
    

    Results for (A=1) OR ( (B=1) AND (C=1) ) are the same.

    Results for ( (A=1) OR (B=1) ) AND (C=1) :

    A   B   C   Result
    0   0   0   False
    0   0   1   False
    0   1   0   False
    0   1   1   True
    1   0   0   False
    1   0   1   True
    1   1   0   False
    1   1   1   True
    

提交回复
热议问题