SQL NOT IN仍包含应排除的行

时间:2013-10-21 13:16:51

标签: mysql sql notin

我有以下语句来查找包含某些值但排除其他值的行:

SELECT * 
FROM tests 
WHERE author = 4  
OR id = -999 
OR id = 276 
OR id = 343 
OR id = 197 
OR id = 170 
OR id = 1058 
OR id = 1328 
OR id = 1417 
AND is_deleted = 0 
AND id NOT IN (457, 2409, 173, 400, 167, 277, 163, 404, 2222, 24, 26, 
               2457, 16, 25, 1639, 2224, 1804, 2308, 197, 461, 1442, 
               1594, 460, 1235, 1814, 2467, 168, 172, 170, 171, 2223, 2535, 2754)

但是,根据NOT IN列表,我仍然会获得应该排除的行。例如,即使tests.author = 4,也应排除id为16的测试。但它在查询中返回,我不想要。

该语句是根据情况以编程方式创建的。

我正在制作语法错误吗?

4 个答案:

答案 0 :(得分:3)

看看SQL Server's operator precedence。您会看到and的优先级高于or

说你正在寻找一辆红色或蓝色的快车。如果你写:

where speed = 'fast' and color = 'green' or color = 'blue'

SQL Server将读取:

where (speed = 'fast' and color = 'green') or color = 'blue'

为了回应您的查询,SQL Server可能会返回一辆缓慢的蓝色汽车。

答案 1 :(得分:0)

将您的查询更改为:

SELECT * 
FROM tests 
WHERE (author = 4  OR id = -999 OR id = 276 OR id = 343 OR id = 197 OR id = 170 OR id = 1058 OR id = 1328 OR id = 1417) 
      AND is_deleted = 0
      AND id NOT IN (457, 2409, 173, 400, 167, 277, 163, 404, 2222, 24, 26, 2457, 16, 25, 1639, 2224, 1804, 2308, 197, 461, 1442, 1594, 460, 1235, 1814, 2467, 168, 172, 170, 171, 2223, 2535, 2754)

您必须将所有or括在括号中。

答案 2 :(得分:0)

试试这个::

SELECT 
* 
FROM tests 
WHERE 
(author = 4  
OR 
id in (-999,276 ,343 ,197 ,170 ,1058 ,1328 ,1417) 
AND is_deleted = 0 )
AND id NOT IN (457, 2409, 173, 400, 167, 277, 163, 404, 2222, 24, 26, 2457, 16, 25, 1639, 2224, 1804, 2308, 197, 461, 1442, 1594, 460, 1235, 1814, 2467, 168, 172, 170, 171, 2223, 2535, 2754)

答案 3 :(得分:0)

Omair你错放了'''首先要清楚你要选择哪个作者。
假设我们需要,
  作者= 4或其id包含在-999,343,197等中且其删除状态= 0且ID不能在457,2409 ......等的作者。 你做的是,

  

author = 4 OR id = -999 OR id = 276 ...
  AND is_deleted = 0
  AND id NOT IN(457,2409,173,400,167,277,163,404,2222,24,26 ......)

根据operator precedence解释为

  

(作者= 4)或(id = -999或id = 276 ...
  AND is_deleted = 0
  AND id NOT IN(457,2409,173,400,167,277,163,404,2222,24,26,......)
  )

在这里,我们只需添加适当的'('来区分我们需要的条件

  

((作者= 4)或(id = -999或id = 276 ......)
  AND(is_deleted = 0)
  AND(不在(457,2409,173,400,167,277,163,404,2222,24,26 ......))   )

所以你可以用适当的括号来改变SQL,

  

选择   *   从测试中   WHERE
  ((作者= 4)或者身份证明(-999,276,343,197,170,1058,1328,1417))
  AND(is_deleted = 0)
  AND(id not IN(457,2409,173,400,167,277,163,404,2222,24,26,2457,16,25,1639,2224,1804,2308,197,461,1442,1594, 460,1235,1814,2467,168,172,170,171,2223,2535,2754))