[英]PostgreSQL delete rows that outer join from multiple tables
I am trying to delete rows from table where theire IDs doesnt exist in other 2 tales.我正在尝试从其他 2 个故事中不存在其 ID 的表中删除行。 on PostgreSQL:在 PostgreSQL 上:
table A:表一:
idB数据库 | idC身份证 | age年龄 |
---|---|---|
1 1 | 4 4 | Three三 |
2 2 | 5 5 | Three三 |
3 3 | 6 6 | Three三 |
table B:表 B:
idB数据库 | name姓名 | age年龄 |
---|---|---|
3 3 | Two二 | Three三 |
7 7 | Two二 | Three三 |
table C:表 C:
idC身份证 | name姓名 | age年龄 |
---|---|---|
4 4 | Two二 | Three三 |
5 5 | Two二 | Three三 |
6 6 | Two二 | Three三 |
final table A:决赛桌A:
idB数据库 | idC身份证 | age年龄 |
---|---|---|
3 3 | 6 6 | Three三 |
first row of table A should be deleted because idC = 4 doesnt exist in table C Second row of table A should be deleted because idB = 2 doesnt exist in table B Third row of table A should be kept idB = 3 exists in table B and idC = 6 exists in table C应删除表 A 的第一行,因为表 C 中不存在 idC = 4 表 A 的第二行应删除,因为表 B 中不存在 idB = 2 应保留表 A 的第三行 idB = 3 存在于表 B 中并且idC = 6 存在于表 C 中
How can I do that?我怎样才能做到这一点?
here is how you can do it:这是你可以做到的:
with tt as (
select a.* from tableA a
left join tableB b on a.idb =b.idb
left join tableC c on a.idC = c.idc
where b.idb is null or c.idc is null
)
delete from tableA a
using tt
where a.idB = tt.idB
and a.idC = tt.idC
Simply use not exists
:只需使用not exists
:
delete from tableA a
where not exists (select 1 from tableB b where b.idB = a.idB) or
not exists (select 1 from tableC c where c.idC = a.idC);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.