从左连接中删除行

Delete rows from a left join

我想加入两个 table 并从中删除。

table1:

|ID| DATA|

table2:

|ID | ID_TAB1|

查询如下所示:

delete from table2 
using table2 as t2 left join table1 as t1 
on t2.ID_TAB1=t1.ID 
where t1.DATA='xxx';

问题是还有第三个table:

table3:

|ID|ID_TAB2|

当我 运行 我的声明失败时说

Update or deleting on table table2 violates foreign key contraint on table table3

我确定 table3 中没有数据连接到带有 t1.DATA='xxx' 的行,所以为什么会出现此错误?我的查询不正确吗?

你的意思可能是:

delete from table2 
 using table1
where  table2.ID_TAB1=table1.ID 
  and  table1.DATA='xxx';

它与您的查询有何不同:

  • 它不会重新引入 table2 的第二个独立实例。否则查询将删除 table2.

  • 中的所有行
  • 连接的 left 资格被滥用。左连接的要点是包括 table2 中没有相应 table1.id 的行,并将缺少的 table1 列设置为 NULL。但是条件t1.DATA='xxx'与此矛盾

这个查询:

delete from table2 
using table2 as t2 left join table1 as t1 
on t2.ID_TAB1=t1.ID 
where t1.DATA='xxx';

实际上是删除 table2 中的所有行(如果 where 中没有匹配项,则删除 none 中的所有行。您在 t2 和 [=13 之间没有任何联系=],所以这本质上是一个交叉连接。

documentation 中的解释(深入):

Do not repeat the target table in the using_list, unless you wish to set up a self-join.

据推测,删除所有行导致第三个 table 出现问题。请注意,您确实想要删除的行也可能导致问题。在这种情况下,您需要使用某种级联逻辑来处理错误。

您可以使用 using 子句并删除 join:

来表达这一点
delete from table2 t2
    using table1 t1 
    where t2.ID_TAB1 = t1.ID  and
          t1.DATA = 'xxx';

或者,只需在 where 子句中使用 exists

delete from table2 t2
    where exists (select 1
                  from table1 t1
                  where t1.id = t2.id_tab1 and t1.data = 'xxx'
                 );