比较和删除同一表中的记录

时间:2019-09-17 12:46:21

标签: postgresql

我有一张称为通讯的桌子。该表包含一些带有contact_id的记录和一些没有contact_id的记录。因此,应将包含contact_id的comm_type和ident列与不包含contact_id的comm_type和ident列进行比较。因此,如果非null的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)

2 个答案:

答案 0 :(得分:0)

我还没有测试过这些,自从我做了这样的事情已经有一段时间了,但是请参阅下文。

在执行此操作之前,将每个语句的第一条语句替换为“ 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;

答案 1 :(得分:0)

我认为您的原始语句很接近,只是反转了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);