【问题标题】:how to find duplicate records in a table within a predefined time period in sql如何在sql中的预定义时间段内查找表中的重复记录
【发布时间】:2015-09-19 21:00:48
【问题描述】:

例如,我有下表

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 小时内找到相同数字的重复行。我应该输出数字和时间戳。
  • 添加了来自 cmets 的问题

标签: mysql sql duplicates


【解决方案1】:

只用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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    • 2015-02-14
    相关资源
    最近更新 更多