在 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 )