使用SQL AND OR一起工作

时间:2016-06-22 12:45:14

标签: sql sql-server logical-operators

我正在尝试使用下面的sql语句来获取城市是亚特兰大的记录,而分类法代码可以是2个不同的值。它没有正常工作,因为它不是给我只是亚特兰大。如果我删除了最后一个OR条件,它可以完美地运行,但我需要让它成为分类值。

SELECT NPI, ...
FROM  NPIData
WHERE ([Provider Business Mailing Address City Name] = 'ATLANTA')
  AND ([Healthcare Provider Taxonomy Code_1] = '122300000X')
   OR ([Healthcare Provider Taxonomy Code_1] = '1223G0001X')

任何想法我做错了什么?

2 个答案:

答案 0 :(得分:12)

OR的优先级低于AND,因此您应该使用括号:

WHERE [Provider Business Mailing Address City Name] = 'ATLANTA' 
  AND ([Healthcare Provider Taxonomy Code_1] = '122300000X' OR
       [Healthcare Provider Taxonomy Code_1] = '1223G0001X')

这里更好的选择就是使用in

WHERE [Provider Business Mailing Address City Name] = 'ATLANTA'
  AND [Healthcare Provider Taxonomy Code_1] in ('122300000X', '1223G0001X')

答案 1 :(得分:1)

尝试:

WHERE     ([Provider Business Mailing Address City Name] = 'ATLANTA')
AND ([Healthcare Provider Taxonomy Code_1] = '122300000X' OR [Healthcare Provider Taxonomy Code_1] = '1223G0001X')