MySQL CHECK 约束
MySQL CHECK 约束
The CHECK
constraint is used to limit the value range that can be placed in a column.(CHECK 约束用于限制可以放入列中的值的范围。)
If you define a CHECK
constraint on a column it will allow only certain values for this column.(如果在列上定义 CHECK 约束,它将只允许该列的特定值。)
If you define a CHECK
constraint on a table it can limit the values in certain columns based on values in other columns in the row.(如果在表上定义 CHECK 约束,它可以基于行中其他列的值来限制某些列中的值。)
CHECK on CREATE TABLE
The following SQL creates a CHECK
constraint on the "Age" column when the "Persons" table is created. The CHECK
constraint ensures that the age of a person must be 18, or older(以下 SQL 在创建 "Persons" 表时,在 "Age" 列上创建了一个 CHECK 约束。CHECK 约束确保一个人的年龄必须是 18 岁或以上。)
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);
To allow naming of a CHECK
constraint, and for defining a CHECK
constraint on multiple columns, use the following SQL syntax(要允许命名 CHECK 约束,以及为多个列定义 CHECK 约束,请使用以下 SQL 语法)
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255),
CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')
);
CHECK on ALTER TABLE
To create a CHECK
constraint on the "Age" column when the table is already created, use the following SQL(要在表已创建后,在 "Age" 列上创建 CHECK 约束,请使用以下 SQL)
ALTER TABLE Persons
ADD CHECK (Age>=18);
To allow naming of a CHECK
constraint, and for defining a CHECK
constraint on multiple columns, use the following SQL syntax(要允许命名 CHECK 约束,以及为多个列定义 CHECK 约束,请使用以下 SQL 语法)
ALTER TABLE Persons
ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sandnes');
DROP a CHECK Constraint (删除 CHECK 约束)
To drop a CHECK
constraint, use the following SQL(要删除 CHECK 约束,请使用以下 SQL)
ALTER TABLE Persons
DROP CHECK CHK_PersonAge;