MySQL查询删除除了每小时最大时间的数据之外的所有数据

时间:2016-03-27 12:32:37

标签: mysql sql database

我在生产环境中部署了opensips,并且已经注册了超过一千个用户,并且每个SIP电话在1分钟后刷新其注册。我写了一个触发器,在每次注册软电话时在location_history表中插入一行。表registration_history保留每个sip用户的注册记录。位置记录的描述是:

id int(10)unsigned username char(64)
domain char(64)
联系字符(255)
收到char(128)
path char(255)
到期日期时间
q float(10,2)
callid char(255)
cseq int(11)
last_modified日期时间
flags int(11)
cflags char(255)
user_agent char(255)
socket char(64)
方法int(11)
sip_instance char(255)
attr char(255)

现在我想在registration_history中只保留一小时内最长过期时间的记录,并希望删除其余记录。请指导我如何做到这一点。 我已经跟随@tommcatt在this线程中提出的查询,但数据库中仍有一小时的多条记录。我的疑问是:

DELETE  ENTRY FROM location_history ENTRY
LEFT JOIN(
  SELECT  username, Date( expires ) TheDate, Hour( expires ) TheHour, Max( expires ) MaxTime
  FROM    location_history  WHERE expires BETWEEN '2016-03-26 00:00:00' and '2016-03-27 00:00:00'
  GROUP BY  username, TheDate, TheHour
) AS T1
  ON  T1.MaxTime = ENTRY.expires
  WHERE T1.MaxTime is null AND ENTRY.expires BETWEEN '2016-03-26 00:00:00' and '2016-03-27 00:00:00'

此Query每天在cron中执行,但不按照我的要求工作。执行后,一小时内仍有多条记录。

1 个答案:

答案 0 :(得分:1)

据推测,您的意思是每个用户名一个条目。如果是这样,您需要在for a in list1: for b in list2: if a.val == b.val: #do xyz 子句中包含该内容:

on

编辑:

如果您每小时只需要一条记录,请从子查询中删除DELETE lh FROM location_history lh LEFT JOIN (SELECT username, Date(expires) as TheDate, Hour(expires) as TheHour, Max(expires) as MaxTime FROM location_history WHERE expires BETWEEN '2016-03-26' and '2016-03-27' GROUP BY username, TheDate, TheHour ) lh2 ON lh2.MaxTime = lh.expires AND lh2.username = lh.username WHERE lh2.MaxTime is null AND lh.expires BETWEEN '2016-03-26' and '2016-03-27';

username