英文:
Postgres check constraint on `TEXT[]` using a normalized solution
问题
类似于其他提出的问题,但尚未找到对TEXT[]
的规范化解决方案:
- 未使用另一个表作为检查
https://dba.stackexchange.com/questions/250659/constrain-array-values-to-an-allowed-set-of-values
- 与上述解决方案相同,但提及了一个规范化解决方案
- 类似
https://stackoverflow.com/questions/10923213/postgres-enum-data-type-or-check-constraint
- 很好的答案,是一个规范化的解决方案,但仅适用于
TEXT
,而不是TEXT[]
我有两个表,articles
和valid_tags
。valid_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[]
:
- 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
- similar
https://stackoverflow.com/questions/10923213/postgres-enum-data-type-or-check-constraint
- great answer and is a normalized solution but only for
TEXT
, notTEXT[]
I have two tables articles
and valid_tags
. valid_tags
holds text values that are only allowed. When an article is INSERT
ed 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论