简体   繁体   中英

MySQL - delete entry created within seconds/range

I am using MySQL database with following structure:

 sensor value timestamp 1 10 2017-01-25 06:00:00 2 12 2017-01-25 06:20:00 2 12 2017-01-25 06:20:05 3 30 2017-01-25 06:23:00

As you can see for sensor 2 there are multiple entries, which were created within a few seconds. I would like to delete one of those 2 entries, which have been created in a time range of 10 seconds. How can I select/delete them?

Can someone help me with this?

You can use a IN clause on the max timestamp tuple

 delete from my_table 
 where (sensor, timestamp) in (
     select sensor, max(timestamp)
     from my_table 
     group by sensor,   
     having count(*) >1

 )

and for time range for duplicated deletion of 10 seconds

delete from my_table 
where (sensor, timestamp) in (

  select sensor, max(timestamp)
  from my_table 
  group by sensor,  UNIX_TIMESTAMP(timestamp) DIV 10 
)

and for avoid the select/delete table you could use a join on a subselect

 delete from my_table 
 inner join (

  select sensor, max(timestamp) my_max
  from my_table 
  group by sensor,  UNIX_TIMESTAMP(timestamp) DIV 10 

 ) t on t.sensor = my_table.sensor and  t.my_max = my_table.timestamp 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM