Home  >  Article  >  Database  >  How to establish constraints in mysql

How to establish constraints in mysql

coldplay.xixi
coldplay.xixiOriginal
2020-09-11 16:12:293882browse

Mysql method of establishing constraints: 1. When creating a table, the code is [constraint index name foreign key (foreign key column)]; 2. After the table creation is completed, the primary key constraint [alter table table_name add primary key (field)].

How to establish constraints in mysql

Related learning recommendations: mysql tutorial(video)

mysql establishment Constraint method:

First method: 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
)

Second method: After the table creation is completed

1.主键约束
添加:alter table  table_name add primary key (字段)
删除:alter table table_name drop primary key
2.非空约束
添加:alter  table table_name modify 列名 数据类型  not null 
删除:alter table table_name modify 列名 数据类型 null
3.唯一约束
添加:alter table table_name add unique 约束名(字段)
删除:alter table table_name drop key 约束名
4.自动增长
添加:alter table table_name  modify 列名 int  auto_increment
删除:alter table table_name modify 列名 int  
5.外键约束
添加:alter table table_name add constraint 约束名 foreign key(外键列) 
references 主键表(主键列)
删除:
第一步:删除外键
alter table table_name drop foreign key 约束名
第二步:删除索引
alter  table table_name drop  index 索引名
[^1]: 
约束名和索引名一样
6.默认值
添加:alter table table_name alter 列名  set default '值'
删除:alter table table_name alter 列名  drop default

If you want to know more about programming learning, please pay attention to the php training column!

The above is the detailed content of How to establish constraints in mysql. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn