I have an application that is tracking object on a map. I'm storing the object position in a table position. I only want to keep the first position I found the object and the last position I found it.

The first issue I'm facing is to clean the existing records. For some object I have 100 of positions. I was writing the following query to clean the table:

DELETE 
FROM position 
WHERE object_id = 121 
AND `time` NOT IN (SELECT max(`time`) FROM position WHERE object_id = 121)
AND `time` NOT IN (SELECT min(`time`) FROM position WHERE object_id = 121);

But apparently I cannot use the position table in a sub-query of a DELETE statement.

The second issue I have is to delete the MAX(time) record for the object, before to insert the new one. I need to check if I have more than one position for the object before to delete the most recent otherwise I might delete the oldest (an only) record.

Is there way to optimise this process? I'm running MySQL latest version on Ubuntu.

Cheers, Maxime

有帮助吗?

解决方案

How about this?

DELETE a 
FROM position a INNER JOIN (SELECT object_id, min(`time`) min_time, max(`time`) max_time FROM position GROUP BY object_id) b ON a.object_id = b.object_id
WHERE a.object_id = 121
AND a.`time` NOT IN (b.min_time, b.max_time)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top