【问题标题】:Delete all records but one that are fetched by a given query删除除给定查询获取的所有记录之外的所有记录
【发布时间】:2021-08-02 19:22:05
【问题描述】:

我有两个表reminderreminder_users,在这些表之间有一个外键约束,reminder_users 是子记录。我想要做的是删除这些拖表中的几个冗余行。到目前为止,我设法通过以下查询找到冗余行:

select r.name, r.remark, u.user_id, u.deadline , count (*)
from reminder r 
inner join reminder_users u on r.id = u.reminder_id 
and u.user_id = u.user_id 
and u.deadline = u.deadline having count(*)> 1
group by r.name, r.remark, u.user_id, u.deadline

所以冗余行与外键id绑定,子记录具有相同的user_iddeadline,父记录具有相同的名称和相同的备注。

having count 子句指出了多余的行,但我想保留其中一条记录,以便计数 > 1 不再为真,因此我不能在删除查询中使用此子句.此外,为了能够从提醒中删除行,首先必须删除来自提醒用户的子数据。

我猜想使用rowidselect max (rowid) 之类的东西应该有可能,但我不知道如何构建删除查询。

非常感谢任何帮助!

【问题讨论】:

    标签: oracle duplicates sql-delete record


    【解决方案1】:

    你在正确的轨道上。您可以通过删除所有rowid 不是子查询返回的delete duplicate rows

    delete reminder 
    where  rowid not in ( 
      select min ( r.rowid )
      from reminder r 
      inner join reminder_users u 
      on r.id = u.reminder_id 
      and u.user_id = u.user_id 
      and u.deadline = u.deadline 
      group by r.name, r.remark, u.user_id, u.deadline
    )
    

    子查询中不需要having 子句。

    注意:这假设每个reminderreminder_users 中有一行。如果不是这种情况,这也会删除没有用户的提醒,因为子查询不会返回它们。

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 2011-11-06
    • 2012-03-26
    • 2012-10-01
    • 2022-01-01
    • 2011-08-18
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多