从两个表中删除行。 PostgresQL
Delete rows from two tables. PostgressSQL
我尝试从两个表中删除行。我使用 postgresql.
DELETE public.cities, public.color_schemes
FROM public.cities
INNER JOIN public.color_schemes ON public.color_schemes.city_id = public.cities.id
WHERE public.cities.id = 1;
我得到一个错误
ERROR: syntax error at or near "public"
LINE 1: public.
^
SQL state: 42601
Character: 1
在 Postgres 中,您可以使用可更新的 CTE:
with c as (
delete from public.color_schemes
where city_id = 1
)
delete from public.cities
where id = 1;
您的情况很简单,因为城市 ID 在两个表中。在大多数复杂的情况下,您可以 return 使用 returning
在 CTE 中删除的行,并在后续逻辑中使用它。
考虑:
with del as (delete from public.cities where id = 1)
delete from public.color_schemes where city_id = 1
注意:如果 cities
和 color_schemes
之间存在关系(如此处所示),您还可以在子 table 上创建一个引用父 table 与 on delete cascade
子句。使用此技术,当您删除父 table 中的记录时,数据库会在后台为您处理从属 table 中的删除。类似于:
alter table public.color_schemes
add constraint color_schemes_city
foreign key (city_id)
references public.cities(id)
on delete cascade;
我尝试从两个表中删除行。我使用 postgresql.
DELETE public.cities, public.color_schemes
FROM public.cities
INNER JOIN public.color_schemes ON public.color_schemes.city_id = public.cities.id
WHERE public.cities.id = 1;
我得到一个错误
ERROR: syntax error at or near "public"
LINE 1: public.
^
SQL state: 42601
Character: 1
在 Postgres 中,您可以使用可更新的 CTE:
with c as (
delete from public.color_schemes
where city_id = 1
)
delete from public.cities
where id = 1;
您的情况很简单,因为城市 ID 在两个表中。在大多数复杂的情况下,您可以 return 使用 returning
在 CTE 中删除的行,并在后续逻辑中使用它。
考虑:
with del as (delete from public.cities where id = 1)
delete from public.color_schemes where city_id = 1
注意:如果 cities
和 color_schemes
之间存在关系(如此处所示),您还可以在子 table 上创建一个引用父 table 与 on delete cascade
子句。使用此技术,当您删除父 table 中的记录时,数据库会在后台为您处理从属 table 中的删除。类似于:
alter table public.color_schemes
add constraint color_schemes_city
foreign key (city_id)
references public.cities(id)
on delete cascade;