Mysql查询删除重复

问题描述 投票:0回答:1

我有一个表(scheduler_history),其中包含用于测试的资源分配的信息/历史记录。记录的信息包括分配的日期时间和释放日期时间以及同一个表中的交叉引用键,

通过筛选key可以从表中看到分配和释放

select * from scheduler_history ac where ac.key = "Hp8INWFYlT"

# id, ate_unit_type, action_type, reason, created_date, modified, assigned_unit_id, key
68337, VHC25, 2, SOAK-TEST, 2023-11-01 18:56:55.415452, 2023-11-01 18:56:55.415483, 37, Hp8INWFYlT
68338, VHC25, 2, SOAK-TEST, 2023-11-01 18:56:55.415523, 2023-11-01 18:56:55.415542, 156, Hp8INWFYlT
68392, VHC25, 9, , 2023-11-02 10:00:45.371648, 2023-11-02 10:00:45.371678, 37, Hp8INWFYlT
68393, VHC25, 9, , 2023-11-02 10:00:45.371716, 2023-11-02 10:00:45.371732, 156, Hp8INWFYlT

其中action_type列表示分配动作,2表示单位分配成功,9表示分配的单位释放

我想为每个分配的单元提取自分配以来所经过的时间,因此这将是释放创建日期减去分配的创建日期,

所以有这样的查询给我重复:

select TIMESTAMPDIFF(minute,his.created_date, aff.created_date) as "Total Time in use(minute)", his.created_date as "Veeahub Assigned Date", aff.created_date as "Veeahub Released Date", aff.key as "Assignment Key", his.reason as "Assigned Reason"
from scheduler_history his
inner join (select ab.created_date, ab.key, ab.action_type
from scheduler_history ab
where ab.action_type = 9) aff on aff.key = his.key
where his.action_type = 2 and his.key = "Hp8INWFYlT"

产生重复项

# Total Time in use(minute), Veeahub Assigned Date, Veeahub Released Date, Assignment Key, Assigned Reason
903, 2023-11-01 18:56:55.415452, 2023-11-02 10:00:45.371648, Hp8INWFYlT, SOAK-TEST
903, 2023-11-01 18:56:55.415523, 2023-11-02 10:00:45.371648, Hp8INWFYlT, SOAK-TEST
903, 2023-11-01 18:56:55.415452, 2023-11-02 10:00:45.371716, Hp8INWFYlT, SOAK-TEST
903, 2023-11-01 18:56:55.415523, 2023-11-02 10:00:45.371716, Hp8INWFYlT, SOAK-TEST

知道为什么重复或如何构建代码,以获得我真正想要的东西 我想要拥有 :

# Total Time in use(minute), Veeahub Assigned Date, Veeahub Released Date, Assignment Key, Assigned Reason
903, 2023-11-01 18:56:55.415452, 2023-11-02 10:00:45.371648, Hp8INWFYlT, SOAK-TEST
903, 2023-11-01 18:56:55.415452, 2023-11-02 10:00:45.371716, Hp8INWFYlT, SOAK-TEST
select TIMESTAMPDIFF(minute,his.created_date, aff.created_date) as "Total Time in use(minute)", his.created_date as "Veeahub Assigned Date", aff.created_date as "Veeahub Released Date", aff.key as "Assignment Key", his.reason as "Assigned Reason"
from scheduler_history his
inner join (select ab.created_date, ab.key, ab.action_type
from scheduler_history ab
where ab.action_type = 9) aff on aff.key = his.key
where his.action_type = 2 and his.key = "Hp8INWFYlT"
sql mysql mysql-workbench
1个回答
0
投票

为了实现数据完整性,请将 UNIQUE INDEX 添加到表中。

DELETE FROM 
  scheduler_history 
WHERE 
  id IN (
    select id 
  from 
      scheduler_history his 
      inner join (
        select 
          ab.created_date, 
          ab.key, 
          ab.action_type 
        from 
          scheduler_history ab 
        where 
          ab.action_type = 9
      ) aff on aff.key = his.key 
    where 
      his.action_type = 2 
      and his.key = "Hp8INWFYlT"
  )
© www.soinside.com 2019 - 2024. All rights reserved.