限制MySQL的子数量的约束

时间:2013-11-07 17:49:36

标签: mysql sql

我有一个看起来像

的数据库
Root
    Child Table 1
        Child table referencing 1
    Child Table 2
    Child Table 3
    Child Table N
         Child Table referencing N

给我的一个要求是限制root中每行的子节点数。

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

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

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

1 个答案:

答案 0 :(得分: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 )