使用 If 结构的约束



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

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;
}

这样的事情可能吗?

请注意,MySQLCHECK约束仅在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
)
);

最新更新