0

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

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 行。

等等

我知道我可以在我的程序的业务逻辑中构建一组检查,但我想知道是否有一种方法可以在数据库中包含一组约束来为我进行完整性检查?外键引用选项似乎都没有做我想要的。

4

1 回答 1

1

在 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 )
于 2013-11-07T18:15:12.670 回答