英文:
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 ('Support', 'Payment') AND
opened_at >= '2022-03-01 00:00:00')
OR C.dv_subcategory = 'Research'
You should write it as:
<!-- language: sql -->
WHERE C.dv_assignment_group IN ('Support', 'Payment') AND
(opened_at >= '2022-03-01 00:00:00' OR C.dv_subcategory ='Research')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论