Java - MySQL查询where子句在ID添加到时间时失败

时间:2015-03-04 11:41:44

标签: java mysql where

我希望搜索传感器事件的数据库,并删除其时间戳等于或减去十秒且其传感器ID在已批准ID列表中的事件。

当我仅使用time参数运行查询时,结果集符合预期,但是当添加sensorID参数时,它似乎返回满足sensorID要求的所有传感器事件,但忽略了时间戳要求。

查询:

"SELECT * FROM events WHERE timestamp BETWEEN " + visionTime + " - INTERVAL 10 SECOND AND " + visionTime + " AND sensorID = 34035434 OR sensorID = 34035492 OR sensorID = 34035426 OR sensorID = 34035482 OR sensorID = 34035125 OR sensorID = 34035498 OR sensorID = 34035508 OR sensorID = 34035444 OR sensorID = 34035418 OR sensorID = 34035466 OR sensorID = 34035128 OR sensorID = 34035119 OR sensorID = 34035448 OR sensorID = 34037294 OR sensorID = 34035549;"

1 个答案:

答案 0 :(得分:4)

您需要在or条件下使用括号,如下所示。原因是首先它会检查and条件并在之后添加多个或没有括号,并且将满足其中一个或条件,从而完全忽略前一个and

所以它更像是

select * from table where col='a' and col2 = 'b' and (col3 = 'c' or col3 = 'd') 

上述内容将返回col = 'a'col2='b'以及col3c or d

的位置

查询中的相同内容应为

"SELECT * FROM events 
   WHERE timestamp BETWEEN " + visionTime + " - INTERVAL 10 SECOND 
   AND " + visionTime + "
   AND ( sensorID = 34035434 
    OR sensorID = 34035492 
    OR sensorID = 34035426 
    OR sensorID = 34035482 
    OR sensorID = 34035125 
    OR sensorID = 34035498 
    OR sensorID = 34035508 
    OR sensorID = 34035444 
    OR sensorID = 34035418 
    OR sensorID = 34035466 
    OR sensorID = 34035128 
    OR sensorID = 34035119 
    OR sensorID = 34035448 
    OR sensorID = 34037294 
    OR sensorID = 34035549 
  )"