gpt4 book ai didi

mysql - 使用 If 结构的约束

转载 作者:行者123 更新时间:2023-12-04 10:47:38 25 4
gpt4 key购买 nike

我有一个数据表,需要一些自定义约束。数据表如下:

ID    int
Val_1 int
Val_2 int
Val_3 int

我需要的是以下内容:
If (Val_1 == A)
{
Val_2 cant be NULL;
}
else if (Val_1 == B)
{
Val_3 cant be NULL;
}
else if (Val_1 == C)
{
Val_2 AND Val_3 cant be NULL;
}
else if (Val_1 == D)
{
Val_2 OR Val_3 cant be NULL;
}

这样的事情甚至可能吗?

最佳答案

请注意 MySQL CHECK约束仅从 MySQL 8.0.16 开始强制执行。在此之前,它们被接受并被默默地忽略。

假设您使用的是 MySQL 8.0.16 或更高版本,您可以执行以下操作:

create table t (
id varchar(1),
val_1 int,
val_2 int,
val_3 int,
constraint my_extra_constraint check (
val_1 = 'A' and val_2 is not null or
val_1 = 'B' and val_3 is not null or
val_1 = 'C' and val_2 is not null and val_3 is not null or
val_1 = 'D' and (val_2 is not null or val_3 is not null)
or val_1 not in ('A', 'B', 'C', 'D') -- remove this line if needed
)
);

关于mysql - 使用 If 结构的约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59630535/

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