如何在sql中的预定义时间段内在表中查找重复记录

时间:2015-09-17 12:48:29

标签: mysql sql duplicates

例如,我有以下表格

Mobile number  Timestamp  
123456         17-09-2015 11:30 
455677         17-09-2015 12:15
123456         17-09-2015 12:25  
453377         17-09-2015 13:15

如果现在是11:30,我想扫描我的桌子并在过去1小时内找到具有相同数字的行。

那是我的SQL语句:

select a.number, a.time
from mytable a inner join
     (select number, time
      from mytable b
      where time>=now()-Interval 1 hour and time<=now ()
      group by number
      Having count(*) > 1
     ) b
     on a.number = b.number and a.time = b.time 

我想在1小时内找到相同数字的重复行。我应该输出数字和时间戳。

1 个答案:

答案 0 :(得分:0)

如何使用exists

select t.*
from mytable t
where t.time >= now() - Interval 1 hour and
      t.time <= now() and
      exists (select 1
              from mytable t2
              where t2.number = t.number and
                    t2.time >= now() - Interval 1 hour and
                    t2.time <= now () and
                    t2.time <> t.time
             );

但是,我怀疑您的查询问题是加入time。只需从子查询和on子句中删除时间,您将获得所有数字。或者,使用group by

select t.number, group_concat(time)
from mytable t
where t.time >= now() - Interval 1 hour and
      t.time <= now() 
group by t.number
having count(*) > 1;