Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Postgresql 比较和删除同一表中的记录_Postgresql - Fatal编程技术网

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

Postgresql 比较和删除同一表中的记录,postgresql,Postgresql,我有一张桌子叫“交流”。此表包含少数带有contact_id的记录和少数没有contact_id的记录。因此,包含contact_id的comm_type和Identit列应与不包含contact_id的comm_type和Identit列进行比较。因此,如果非空联系人id的通信类型和标识与空联系人id的通信类型和标识匹配,则应消除空联系人的通信类型和标识 id contact_id comm_type ident 109901; 114351; 3

我有一张桌子叫“交流”。此表包含少数带有contact_id的记录和少数没有contact_id的记录。因此,包含contact_id的comm_type和Identit列应与不包含contact_id的comm_type和Identit列进行比较。因此,如果非空联系人id的通信类型和标识与空联系人id的通信类型和标识匹配,则应消除空联系人的通信类型和标识

id       contact_id   comm_type    ident  
109901;   114351;         3      "1111111111";
97631;    102177;         2      "Konnection hub#12403";
102924;   109096;         3      "1111111111";
在这种情况下,应删除不包含联系人id的前两条记录,因为其通信类型和标识与包含联系人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)

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

在执行此操作之前,请使用“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 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);

实际上,这不满足条件。。。。!因为每个并没有联系人id的通信类型和标识都应该和包含联系人id的通信类型和标识记录进行比较。若在包含联系人id和并没有联系人id的记录中存在相同的通信类型和标识数据,那个么只有那个些数据应该被删除。是的。。。。!!!!它起作用了,谢谢你。事实上,我有点困惑,并把它写反了。但事实上,我有一个疑问,这个相关子查询是否适用于包含更多列的表?因为我们将简单地提到select 1或select*,所以有时外部查询需要删除哪些输入?是的,任何子查询都可以完全访问它引入的表,无论是否相关。此外,子查询已完成到它所属的更高查询。它的关联性在于对更高层次的引用。此访问不一定通过较低的子查询。即子查询的子查询可能无法访问父(主)查询的列。
DELETE Table1
FROM Table1
JOIN Table2 ON Table1.contact_id != Table2.contact
AND Table1.comm_type = Table2.comm_type
AND Table1.ident = Table2.ident;
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);