作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个看起来像这样的数据库
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/
我需要对反正切值执行泰勒级数 50 次。表示 arctan Taylor 级数的域之间的 50 个数字,即 [-1,1]。我已经用手动用户输入对其进行了测试并且它工作正常,但是我在代码中递增 0.01
我在网上看了几个小时,想看看我是否能找到解决方案,虽然我已经找到了很多解决方案,但我教授的指示如下: Write a program to estimate PI (π) using the foll
我最近在编程测试中被问到这个问题。我似乎无法理解为什么我会得到答案“1”。我是 C 编程语言的初学者。 这是我的代码: #include int main() { float c = 0;
我是一名优秀的程序员,十分优秀!