[英]Java - MySQL query where clause failing when ID added to time
I am looking to search a database of sensor events and remove the events where their timestamp is equal to or minus ten second and whose sensor ID are within a list of approved ID's. 我正在寻找一个传感器事件数据库,并删除其时间戳等于或减去十秒且传感器ID在批准ID列表内的事件。
When I run the query with just the time parameter the result set is as expected but when the sensorID parameter is added it seems to be returning all the sensor events that meet the sensorID requirements but ignores the timestamp requirement. 当我仅使用时间参数运行查询时,结果集符合预期,但是当添加sensorID参数时,它似乎将返回所有符合sensorID要求但忽略时间戳要求的传感器事件。
The query: 查询:
"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;"
You need to use parentheses for the or
conditions something as below. 您需要在
or
条件中使用括号,如下所示。 The reason is first it will check the and
condition and adding multiple or without parentheses after and will satisfy one of the or condition resulting complete ignore of the previous and
原因是首先它将检查
and
条件,并在其后添加多个或不带括号,并满足or条件之一,从而完全忽略前一个and
So it will be more like 所以会更像
select * from table where col='a' and col2 = 'b' and (col3 = 'c' or col3 = 'd')
The above will return where col = 'a'
and col2='b'
and col3
is either c or d
以上将返回
col = 'a'
和col2='b'
且col3
为c or d
The same thing in your query should be as 您查询中的相同内容应为
"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
)"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.