In the MYSQL database, you can perform some operations on various items of the table when creating a table, such as adding primary key constraints or non-null constraints; you can also add constraints and delete constraints after creating the table. The following article will give you a detailed understanding, I hope it will be helpful to you.
What are constraints?
Constraints are actually restrictions on the data in the table; the purpose is to ensure that the records in the table are complete and valid.
Commonly used constraints are:
1, non-null constraint (not null)
2, unique constraint (unique)
3, primary key constraint ( primary key)
4. Foreign key constraint(foreign key)
5. Check constraint (currently not supported by MySQL, supported by Oracle)
##mysql Methods to add and delete constraints:
1. Add constraints when creating the table
create table table_name( 列名1 数据类型 (int) primary key auto_increment, 列名2 数据类型 not null, 列名3 数据类型 unique, 列名4 数据类型 default '值', constraint 索引名 foreign key(外键列) references 主键表(主键列) on delete cascade | on delete set null )
2. Add constraints after the table creation is completed And delete constraints
1), non-null constraints Add non-null constraintsalter table table_name modify 列名 数据类型 not nullDelete non-null constraints
alter table table_name modify 列名 数据类型 null2), unique Constraint Add unique constraint
alter table table_name add unique 约束名(字段)Delete unique constraint
alter table table_name drop key 约束名3), primary key constraint
alter table table_name add primary key (字段)Delete primary key constraints
alter table table_name drop primary key4), foreign key constraints Add foreign key constraints
alter table table_name add constraint 约束名 foreign key(外键列)Delete foreign key constraints
alter table table_name drop foreign key 约束名5), automatic growth Constraints Add automatic growth constraints
alter table table_name modify 列名 int auto_incrementDelete automatic growth constraints
alter table table_name modify 列名 intRecommended related video tutorials: "
MySQL Tutorial"
The above is the detailed content of How to add constraints in mysql?. For more information, please follow other related articles on the PHP Chinese website!