删除重复号码状态是否存在?

时间:2015-07-20 10:56:44

标签: mysql database

如何将副本删除到新表中?

例如在表格中:

id |   number      |    status    | statusdate 
1  | 12121312      |   Processing | 01/06/2015  12:32:00
2  | 12121312      |   Processing | 02/06/2015  13:37:00
3  | 12121312      |   Processing | 03/06/2015  14:29:00
4  | 99999999      |   Processing | 03/06/2015  15:33:00
5  | 99999999      |   Completed  | 03/06/2015  18:39:00
6  | 99999999      |   Completed  | 04/06/2015  19:39:00
  1. id 1到3有重复的号码,但没有“已完成”状态,因此请从最早的日期获取号码

  2. id 4到6,有重复的数字,但确实存在“已完成”状态。从最新的日期获取数字

  3. 在新表中,它应该是这样的:

    id |   number      |    status    | statusdate 
    1  | 12121312      |   Processing | 01/06/2015  12:32:00
    6  | 99999999      |   Completed  | 04/06/2015  19:39:00
    

    怎么办呢?

3 个答案:

答案 0 :(得分:2)

这是一个未经优化的版本:

DELETE FROM table_name as T
WHERE ( 
        number in (SELECT number
                   FROM table_name
                   WHERE status = 'Completed')
        AND statusdate < (SELECT MAX(statusdate)
                          FROM table_name
                          GROUP BY number
                          HAVING number = T.number)
    )
    OR
    (
        number in (SELECT number
                   FROM table_name
                   WHERE status = 'Processing')
        AND statusdate > (SELECT MIN(statusdate)
                          FROM table_name
                          GROUP BY number
                          HAVING number = T.number)                   
    );

这些是删除的记录:

id  number      status      statusdate
2   12121312    Processing  February, 06 2015 13:37:00
3   12121312    Processing  March, 06 2015 14:29:00
4   99999999    Processing  March, 06 2015 15:33:00
5   99999999    Completed   March, 06 2015 18:39:00
6   99999999    Completed   April, 06 2015 19:39:00

只需将SELECT * FROM替换为Fiddle中的DELETE FROM

答案 1 :(得分:2)

用于选择没有重复的记录:

select t1.* 
from tableName t1 JOIN
     tablename t2 on t1.number=t2.number 
                 and t1.status>=t2.status 
                 and t1.statusdate>t2.statusdate
group by t1.status
order by id

结果SQL Fiddle

从表中删除重复项:

delete from tableName
where id NOT IN 
    (select t1.id 
    from tableName t1 JOIN
         tablename t2 on t1.number=t2.number 
                     and t1.status>=t2.status 
                     and t1.statusdate>t2.statusdate
    group by t1.status) as Tbl

答案 2 :(得分:0)

假设项目按时间顺序添加到数据库,这将为您提供所需的ID列表:

SELECT COALESCE(MAX(IF(status='Completed',id,NULL)),MIN(IF(status='Processing',id,NULL))) 
FROM yourtable
GROUP BY number;

然后您可以选择这些行:

SELECT * FROM yourtable 
 WHERE id IN (select coalesce(max(if(status='Completed',id,null)),min(if(status='Processing',id,null))) 
from yourtable
group by number);

或删除其他人,如果需要的话。