Sql 删除两个相关表中的行

Sql 删除两个相关表中的行,sql,delete-row,Sql,Delete Row,表1和表2之间有一个1N关系。表2的“代码”列是表1的外键。 我想删除表1中所有在表2中没有任何相关行的行。我试着 delete * from table1 r inner join table2 a where (r.code!=a.code) 但是这会删除两个表中的所有行…也许这就是您想要的 delete from table1 where code not in ( select code from table2 ) 在运行删除之前,您可能需要验证是否将使用s

表1和表2之间有一个1N关系。表2的“代码”列是表1的外键。 我想删除表1中所有在表2中没有任何相关行的行。我试着

delete * from table1 r 
   inner join table2 a 
      where (r.code!=a.code)

但是这会删除两个表中的所有行…

也许这就是您想要的

delete from table1
where code not in (
  select code from table2
)
在运行删除之前,您可能需要验证是否将使用select查询删除正确的行:

select * from table1
where code not in (
  select code from table2
)
你可以试试这个:

delete from table1 r 
where not exists (select 1 from table2 a where r.code = a.code);

或者可能使用
右侧外部联接

delete from table1 r 
   right join table2 a on a.code = r.code
      where r.code is null

@谢谢,我从问题中复制了陈述,没有注意到这一点