gpt4 book ai didi

mysql - MySQL 中限制子级数量的约束

转载 作者:行者123 更新时间:2023-11-29 13:28:14 25 4
gpt4 key购买 nike

我有一个看起来像这样的数据库

Root
Child Table 1
Child table referencing 1
Child Table 2
Child Table 3
Child Table N
Child Table referencing N

给我的要求之一是限制根中每行的子级数量。

每个根行只能有 4 个 child1 行。

每个根行只能有 12 个 child2 行。

等等

我知道我可以在程序的业务逻辑中构建一组检查,但我想知道是否有一种方法可以在数据库中包含一组约束来为我进行健全性检查? None of the foreign key reference options seem to do what I want

最佳答案

在 MySQL 中,您必须使用触发器来执行此操作,因为 MySQL 不遵守检查约束。该触发器需要查询给定外键值的行数,如果超过您的计数,则会引发错误。所以,类似于:

Create Trigger TrigChildTable
Before Insert
On ChildTable
For Each Row
Begin

If Exists (
Select 1
From ChildTable
Where ParentFKColumn = New.ParentFKColumn
Having Count(*) > 3 -- Max count - 1
)
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Cannot have more than 4 child rows for a given parent';

End

如果 MySQL 遵守检查约束(它不遵守),您可以执行以下操作:

-- add a sequence or counter column
Alter Table ChildTable
Add Sequence int not null;

-- add a unique constraint/index on the foreign key column + sequence
Alter Table ChildTable
Add Constraint UC_Parent_Sequence
Unique ( ParentFKColumn, Sequence )

-- using a check constraint, require that the sequence value
-- be between 0 and 4
Alter Table ChildTable
Add Constraint CK_Sequence Check ( Sequence Between 0 And 4 )

关于mysql - MySQL 中限制子级数量的约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19843047/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com