选择要使用隐式连接删除的行
Selecting lines to delete with an implicit join
我有两个具有多对一关系的 table。我可以使用隐式连接 "child" table 中的 select 项目和父 table 中的条件:
select * from child,parent where child.parentid=parent.id and parent.name like 'foobar%'
是否有更好(更高效、更优雅)的删除子项的方法:
delete from child where child.parentid in (select id from parent where parent.name like 'foobar%')
This answer 提示我可以做:
delete child from child,parent where child.parentid=parent.id and parent.name like 'foobar%'
但是在 PostgreSql 上(通过 SquirrelSQL)我得到一个语法错误...当然我有很长的 table 名字所以实际请求更像是:
delete c from child c, parent p where c.parentid=p.id and p.name like 'foobar%'
请问这个是PG支持的,还是有别的办法?
奖励积分:我可以使用以下方法从两个 table 中删除项目:
delete from child,parent where child.parentid in (select id from parent where parent.name like 'foobar%')
您可以使用 data modifying CTE:
在一个语句中从两个表中删除
with deleted_parent as (
delete from parent
where name like 'foobar%'
returning id
)
delete from child
where id in (select id from deleted_parent)
我建议通过使用 on delete
级联选项创建外键来利用数据库的功能:
alter table child
add constraint child_parent_fk
foreign key (parentid) references parent(id)
on delete cascade;
除了在 table 之间强制执行数据完整性之外,这将在删除父项时管理子项 table 中的删除,因此您只需...
delete from parent where name like 'foobar%'
...放心,children会被相应删除
在 postgres 中,您要执行的操作的语法是使用 "USING"
delete from child C USING parent P where C.parentid=P.id
and P.name like 'foobar%'
我有两个具有多对一关系的 table。我可以使用隐式连接 "child" table 中的 select 项目和父 table 中的条件:
select * from child,parent where child.parentid=parent.id and parent.name like 'foobar%'
是否有更好(更高效、更优雅)的删除子项的方法:
delete from child where child.parentid in (select id from parent where parent.name like 'foobar%')
This answer 提示我可以做:
delete child from child,parent where child.parentid=parent.id and parent.name like 'foobar%'
但是在 PostgreSql 上(通过 SquirrelSQL)我得到一个语法错误...当然我有很长的 table 名字所以实际请求更像是:
delete c from child c, parent p where c.parentid=p.id and p.name like 'foobar%'
请问这个是PG支持的,还是有别的办法?
奖励积分:我可以使用以下方法从两个 table 中删除项目:
delete from child,parent where child.parentid in (select id from parent where parent.name like 'foobar%')
您可以使用 data modifying CTE:
在一个语句中从两个表中删除with deleted_parent as (
delete from parent
where name like 'foobar%'
returning id
)
delete from child
where id in (select id from deleted_parent)
我建议通过使用 on delete
级联选项创建外键来利用数据库的功能:
alter table child
add constraint child_parent_fk
foreign key (parentid) references parent(id)
on delete cascade;
除了在 table 之间强制执行数据完整性之外,这将在删除父项时管理子项 table 中的删除,因此您只需...
delete from parent where name like 'foobar%'
...放心,children会被相应删除
在 postgres 中,您要执行的操作的语法是使用 "USING"
delete from child C USING parent P where C.parentid=P.id
and P.name like 'foobar%'