[英]I have a problem with this query in Postgres
I have a problem with this table in Postgres, it give me this error:我在 Postgres 中的这个表有问题,它给了我这个错误:
ERROR: cannot use subquery in check constraint LINE 66: check(Artista in(Select ID_Artista错误:无法在检查约束 LINE 66 中使用子查询:检查(Artista in(选择 ID_Artista
create table DirigeF(
Artista int references Artista(ID_Artista) on delete cascade,
Film int references Film(ID_Contenuto) on delete cascade,
check(Artista in(Select ID_Artista
from Artista
where tipologia='REGISTA'or'AR')),
constraint DirigeF_PK primary key(Artista, Film)
);
I want to check that Artista in table DirigeF has tipologia='REGISTA' from another table.我想检查 DirigeF 表中的 Artista 是否有来自另一个表的tipologia='REGISTA'。
As the error suggests, you cannot do this with a check constraint.正如错误所暗示的,您不能使用检查约束来执行此操作。 One option is a trigger.一种选择是触发器。 Another is a foreign key constraint -- but that needs to be carefully arranged.另一个是外键约束——但这需要仔细安排。
First you need a column that indicates whether the type in Artista
is "REGISTA" or "AR".首先,您需要一列来指示Artista
中的类型是“REGISTA”还是“AR”。 That would be:那将是:
alter table artista add is_regista_ar bool generated always as
(tipologia in ('REGISTA', 'AR'));
Then create a unique constraint or index:然后创建唯一约束或索引:
alter table artista add unq_artista_tipologia_id
unique (is_regista_ar, id_artista)
Note: This requires Postgres 12+.注意:这需要 Postgres 12+。 But something similar can be done in earlier versions.但是在早期版本中可以做类似的事情。
Then, add a boolean column to your table that is always true
:然后,将 boolean 列添加到您的表中,该列始终为true
:
create table DirigeF (
Artista int references Artista(ID_Artista) on delete cascade,
Film int references Film(ID_Contenuto) on delete cascade,
is_regista_ar bool generated always as true,
constraint fk_artista_tipo_artista foreign key (is_regista_ar, Artista) references Artista(is_regista_ar, ID_Artista),
constraint DirigeF_PK primary key (Artista, Film)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.