【问题标题】:Comparing and deleting records from the same table比较和删除同一张表中的记录
【发布时间】:2019-09-18 00:32:10
【问题描述】:

我有一张叫做交流的桌子。该表包含少量带有contact_id 的记录和少量不带有contact_id 的记录。因此,应该将包含contact_id 的comm_type 和ident 列与不包含contact_id 的comm_type 和ident 列进行比较。所以,如果不为空的contact_id的comm_type和ident与null的contact_id的comm_type和ident匹配,那么null的contact comm_type和ident应该被剔除

id       contact_id   comm_type    ident  
109901;   114351;         3      "1111111111";
97631;    102177;         2      "Konnection hub#12403";
102924;   109096;         3      "1111111111";
id        contact_id   comm_type     ident  
109901;                   3        "1111111111";
97631;                    2        "Konnection hub#12403";
102924;                   4        "Aptech interval";

在这种情况下,应该删除不包含contact_id的前两条记录,因为它的comm_type和ident与包含contact_id的记录匹配。

我已经尝试过这个查询,但这并没有让我得到正确的输出:-


BEGIN;
delete from crm.comm_medium m1 where contact_id is not null and  exists
(select 1 from crm.comm_medium m2 where m2.comm_type_id =m1.comm_type_id and m2.ident=m1.ident and contact_id is null)

【问题讨论】:

    标签: postgresql


    【解决方案1】:

    我还没有测试过这些,我已经有一段时间没有做这样的事情了,但请看下面。

    在执行此操作之前,将每个语句的第一条语句替换为“SELECT *”以恢复将被删除的记录,这样您就可以在执行不可逆转的删除之前测试您的逻辑。

    
    DELETE FROM Table1
    WHERE NOT EXISTS (
        SELECT contact_id
        FROM Table2
        WHERE Table2.contact_id = Table1.contact_id
    )
    AND Table1.comm_type = Table2.comm_type
    AND Table1.ident = Table2.ident
    

    DELETE Table1
    FROM Table1
    JOIN Table2 ON Table1.contact_id != Table2.contact
    AND Table1.comm_type = Table2.comm_type
    AND Table1.ident = Table2.ident;
    

    【讨论】:

    • 其实这不满足条件....!因为每一个没有contact_id的comm_type和ident都应该和每一个包含contact_id的comm_type和ident记录进行比较。如果相同的 comm_type 和 ident 数据存在于包含 contact_id 和没有 contact_id 的记录中,则只应删除那些。
    【解决方案2】:

    我认为您的原始陈述很接近,只是将 NULL 条件颠倒了:

    delete from crm.comm_medium m1 
     where m1.contact_id is null 
       and exists
          (select null 
             from crm.comm_medium m2 
            where m2.comm_type_id = m1.comm_type_id 
              and m2.ident = m1.ident 
              and m2.contact_id is not null);
    

    【讨论】:

    • 是的....!!!!它正在工作,谢谢。其实我有点困惑,把它写反了。
    • 但实际上我有一个疑问,这个相关的子查询是否适用于包含更多列的表?因为我们将简单地提及 select 1 或 select * ,所以有时外部查询需要输入删除?
    • 是的,任何子查询都可以完全访问它引入的表,无论是否相关。此外,子查询已完成它所属的更高查询。使其相关的是对更高级别的引用。这种访问不一定要通过较低的子查询。 IE子查询的子查询可能无法访问父(主)查询的列。
    猜你喜欢
    • 2012-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    • 2017-02-14
    相关资源
    最近更新 更多