Home >Database >Mysql Tutorial >How to establish constraints in mysql?

How to establish constraints in mysql?

青灯夜游
青灯夜游Original
2020-09-30 16:47:214275browse

Method: 1. When creating the table, use the primary key and foreign key keywords after the fields to establish primary key and foreign key constraints; 2. After creating the table, use the "alter table" statement with the primary key, Keywords such as not null and unique are used to establish constraints.

How to establish constraints in mysql?

MYSQL adding constraints

First type: when creating a 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 type: 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

         

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