Tuesday, 28 August 2018

MySQL max () - does not return the max () value

I have a query which I want to return the highest id value in idevent that is within a given range of sensor ID's (sensorID) however the query is not returning the highest value.

The results when I run the query minus the max() statment:
mysql> SELECT * FROM events WHERE timestamp BETWEEN "2015-03-09 10:45:35" - INTERVAL 4000 SECOND AND "2015-03-09 10:45:35" 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);
+---------+---------------------+----------+-------+
| idevent | timestamp           | sensorID | event |
+---------+---------------------+----------+-------+
|  117794 | 2015-03-09 10:14:58 | 34035434 |     9 |
|  117795 | 2015-03-09 10:15:03 | 34035508 |     9 |
|  117796 | 2015-03-09 10:15:17 | 34035508 |     1 |
+---------+---------------------+----------+-------+
3 rows in set (0.00 sec)

The results given when the max() statement is added as a HAVING clause:
mysql> SELECT * FROM events WHERE timestamp BETWEEN "2015-03-09 10:45:35" - INTERVAL 4000 SECOND AND "2015-03-09 10:45:35" 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) HAVING max(idevent);
+---------+---------------------+----------+-------+
| idevent | timestamp           | sensorID | event |
+---------+---------------------+----------+-------+
|  117794 | 2015-03-09 10:14:58 | 34035434 |     9 |
+---------+---------------------+----------+-------+
1 row in set (0.00 sec)

Why is this not returning the lastest value?

This could be done with order by limit, so all you need to add the following at the end of the given first query
order by idevent desc limit 1

0 comments:

Post a Comment