Postgres对`TEXT[]`使用规范化解决方案的检查约束

huangapple go评论50阅读模式
英文:

Postgres check constraint on `TEXT[]` using a normalized solution

问题

类似于其他提出的问题,但尚未找到对TEXT[]的规范化解决方案:

https://stackoverflow.com/questions/57111636/postgres-check-constraint-in-text-array-for-the-validity-of-the-values

  • 未使用另一个表作为检查

https://dba.stackexchange.com/questions/250659/constrain-array-values-to-an-allowed-set-of-values

  • 与上述解决方案相同,但提及了一个规范化解决方案

https://stackoverflow.com/questions/31695205/check-if-value-exists-in-postgres-array-for-partitioning-via-check-constraint

  • 类似

https://stackoverflow.com/questions/10923213/postgres-enum-data-type-or-check-constraint

  • 很好的答案,是一个规范化的解决方案,但仅适用于TEXT,而不是TEXT[]

我有两个表,articlesvalid_tagsvalid_tags包含仅允许的文本值。当插入文章时,tags TEXT[]列必须是有效标签值的数组。我需要将这些值与valid_tags表进行检查。

CREATE TABLE articles (
  tags TEXT[]
);

CREATE TABLE valid_tags (
	name TEXT
);

我正在寻找与 https://stackoverflow.com/questions/10923213/postgres-enum-data-type-or-check-constraint 类似的解决方案,但带有color_id列为TEXT[]的约束。

英文:

Similar to other questions asked but haven't found a normalized solution for TEXT[]:

https://stackoverflow.com/questions/57111636/postgres-check-constraint-in-text-array-for-the-validity-of-the-values

  • does not use another table as a check

https://dba.stackexchange.com/questions/250659/constrain-array-values-to-an-allowed-set-of-values

  • same solution as above but mentions a normalized solution

https://stackoverflow.com/questions/31695205/check-if-value-exists-in-postgres-array-for-partitioning-via-check-constraint

  • similar

https://stackoverflow.com/questions/10923213/postgres-enum-data-type-or-check-constraint

  • great answer and is a normalized solution but only for TEXT, not TEXT[]

I have two tables articles and valid_tags. valid_tags holds text values that are only allowed. When an article is INSERTed the tags TEXT[] column must be an array of valid tag values. I need to check those values against the valid_tags table.

CREATE TABLE articles (
  tags TEXT[]
);

CREATE TABLE valid_tags (
	name TEXT
);

I'm looking for a very similar solution as https://stackoverflow.com/questions/10923213/postgres-enum-data-type-or-check-constraint but with the constraint that column color_id is TEXT[].

答案1

得分: 1

规范和推荐的解决方案是使用数组,而是在您的表之间使用连接表。这将隐式解决该问题。

请注意,虽然您可以编写一个似乎实现您想要的检查约束,但该检查约束是非法的,最终会破坏您的数据库。不要这样做。

英文:

The normalized and recommended solution is not to use an array, but a junction table between your tables. That would solve the problem implicitly.

Note that while you can write a check constraint that seems to do what you want, that check constraint is illegal and will break your database sooner or later. Don't do it.

huangapple
  • 本文由 发表于 2023年5月31日 23:39:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76375214.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定