MYSQL从特定日期的表中删除重复值

时间:2017-12-22 08:09:54

标签: mysql sql join group-by inner-join

我有一个包含三个字段的mysql表和另外idprimary key

host              ipaddress      date
----              ---------      -----
server1.abc.com   10.1.1.1      2011-10-18 22:45:16
server1           10.1.1.1      2011-12-19 21:56:46
server2           11.1.1.1      2011-12-18 21:56:46
server2.abc.com   11.1.1.1      2011-12-17 21:56:46

Here,
host --> varchar
ipaddress --> varchar
date ---> datetime

我想在表格中选择host ip的重复条目 我只想在date like '2011-12-19%'

时检查主机的重复条目

从上表中,我的结果应满足条件date like '2011-12-19%'

host              ipaddress      date
----              ---------      -----
server1.abc.com   10.1.1.1      2011-10-18 22:45:16
server1           10.1.1.1      2011-12-19 21:56:46

我有以下查询工作正常

select t1.*
from tablename t1
join (select ipaddress
      from tablename
      group by ipaddress
      having count(*) >= 2
         and count(case when CAST(date AS DATE) = '2017-12-19' then 1 end) > 0) t2
  on t1.ipaddress = t2.ipaddress

现在,我需要帮助来编写查询以删除date NOT like '2011-12-19%'所在的行 因此,我的表格应该有ipaddress的一个条目date like '2011-12-19%'

host              ipaddress      date
----              ---------      -----
server1           10.1.1.1      2011-12-19 21:56:46

我已移除date -> 2011-10-18 22:45:16的条目,这样就不会在ipaddress

的表格中重复date like '2011-12-19%'

1 个答案:

答案 0 :(得分:1)

您可以DELETE使用JOIN

delete t1
from mytable t1
join (select ipaddress
      from mytable
      group by ipaddress
      having count(*) >= 2
         and count(case when CAST(date AS DATE) = '2011-12-19' then 1 end) > 0) t2
  on t1.ipaddress = t2.ipaddress
where CAST(date AS DATE) != '2011-12-19'

使用此查询可以删除记录

host              ipaddress      date
----              ---------      -----
server1.abc.com   10.1.1.1      2011-10-18 22:45:16

来自你的桌子。

Demo here