OR条件导致WHERE条件在结果中被忽略的原因是什么?

huangapple go评论73阅读模式
英文:

Why does my OR condition cause the WHERE condition to be ignored in the results?

问题

SELECT TOP 50
    C.task
    , C.dv_state
    , C.opened_at
    , C.dv_assignment_group
    , C.dv_subcategory
FROM [dbo.].[sn_customer_task] C WITH (NOLOCK)
WHERE C.dv_assignment_group IN ('支持', '付款') 
AND opened_at >= '2022-03-01 00:00:00'
OR C.dv_subcategory = '研究';
英文:
SELECT TOP 50
    C.task
    , C.dv_state
    , C.opened_at
    , C.dv_assignment_group
    , C.dv_subcategory
FROM [dbo.].[sn_customer_task] C WITH (NOLOCK)
WHERE C.dv_assignment_group IN ('Support', 'Payment') 
AND opened_at >= '2022 3-1- 00:00:00')
OR C.dv_subcategory ='Research;

I would like for the results to return only the data for assignment_group under 'Support' and 'Payment'.

I've tried placing the parentheses around what follows the WHERE and OR clauses.

答案1

得分: 3

"AND" 操作符的优先级比 "OR" 操作符高,所以你当前的代码实际上被解释为:

<!-- 语言: sql -->

    WHERE
        (C.dv_assignment_group IN ('Support', 'Payment') AND
         opened_at >= '2022-03-01 00:00:00')
        OR C.dv_subcategory = 'Research'

你应该将其写成:

<!-- 语言: sql -->

    WHERE C.dv_assignment_group IN ('Support', 'Payment') AND
          (opened_at >= '2022-03-01 00:00:00' OR C.dv_subcategory ='Research')
英文:

The AND operator has greater precedence than the OR operator, so your current code is actually being evaluated as this:

<!-- language: sql -->

WHERE
    (C.dv_assignment_group IN (&#39;Support&#39;, &#39;Payment&#39;) AND
     opened_at &gt;= &#39;2022-03-01 00:00:00&#39;)
    OR C.dv_subcategory = &#39;Research&#39;

You should write it as:

<!-- language: sql -->

WHERE C.dv_assignment_group IN (&#39;Support&#39;, &#39;Payment&#39;) AND
      (opened_at &gt;= &#39;2022-03-01 00:00:00&#39; OR C.dv_subcategory =&#39;Research&#39;)

huangapple
  • 本文由 发表于 2023年3月23日 10:13:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75818739.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定