我应该如何处理数据库中的约束选项?
How should I handle constraining options in a database?
[已编辑问题]
List
table 有:rabbit, cat, dog...
等无数的动物。
Animal
table 什么是限制列表集。例如。仅限于兔子、猫或狗。然而,限制列表集也有像 resctrictToAnimalsWithFur
、restrictToAnimalsStartingWithLetterA
等值
所以基本上,RestrictedList
table 集合完全包含 List
table + 额外值中包含的项目。
我不能将 RestristedList
table 中的值作为 List
table 中的 FK,因为它有其他值。
但是我不想通过将它们放在 RestrictedList
table 中来复制 List
table 中的所有值,因为它看起来多余。
我也不能只删除 List
table 而只有 RestrictedList
table 因为 List
table 用于其他地方。
我对 DB 的了解仅限于如何在不复制 RestrictedList
table.
中的整个 List
table 的情况下解决此类问题
我该怎么做?这是应用层必须要解决的事情吗?或者数据库可以解决吗?
我将其称为 ExtendedList
而不是 RestrictedList
,因为它包含更多元素...
无论如何,避免重复的一种方法是让 table restrictions
只包含 RestrictedList
中不在 list
中的那些条目.
则animal
有两个外键列:list_id
,指向list
,和restriction_id
,指向restriction
。
检查约束确保恰好设置了其中之一:
ALTER TABLE animals ADD CHECK
(CAST (list_id IS NULL AS integer)
+ CAST (restriction_id IS NULL AS integer) = 1);
[已编辑问题]
List
table 有:rabbit, cat, dog...
等无数的动物。
Animal
table 什么是限制列表集。例如。仅限于兔子、猫或狗。然而,限制列表集也有像 resctrictToAnimalsWithFur
、restrictToAnimalsStartingWithLetterA
等值
所以基本上,RestrictedList
table 集合完全包含 List
table + 额外值中包含的项目。
我不能将 RestristedList
table 中的值作为 List
table 中的 FK,因为它有其他值。
但是我不想通过将它们放在 RestrictedList
table 中来复制 List
table 中的所有值,因为它看起来多余。
我也不能只删除 List
table 而只有 RestrictedList
table 因为 List
table 用于其他地方。
我对 DB 的了解仅限于如何在不复制 RestrictedList
table.
List
table 的情况下解决此类问题
我该怎么做?这是应用层必须要解决的事情吗?或者数据库可以解决吗?
我将其称为 ExtendedList
而不是 RestrictedList
,因为它包含更多元素...
无论如何,避免重复的一种方法是让 table restrictions
只包含 RestrictedList
中不在 list
中的那些条目.
则animal
有两个外键列:list_id
,指向list
,和restriction_id
,指向restriction
。
检查约束确保恰好设置了其中之一:
ALTER TABLE animals ADD CHECK
(CAST (list_id IS NULL AS integer)
+ CAST (restriction_id IS NULL AS integer) = 1);