MySQL约束

目录

 

1.主键约束:

        自定义主键

        联合主键:

2.删除主键:

3.自增约束:

主键自增长:

指定自增长字段初始值:

创建表后指定自增长字段初始值:

4.非空约束

5.唯一约束

6.默认约束


 

1.主键约束:

其值能唯一的标识表中的每一行(唯一约束+非空约束)

        自定义主键

(1)create table 表名 (

 

列名1 类型 ,

列名2 类型 primary key

);

(2)create table 表名(

...

primary key(字段名)

);

        联合主键:

create table 表名(

...

...

primary key (字段名1,字段名2)

);

2.删除主键:

alter table 表名 drop primary key;

3.自增约束:

添加自增长的列为整数列 必须有唯一索引具备非空属性

主键自增长:

create table 表名(

列名1 数据类型 primary key auto_increment,

...

);

指定自增长字段初始值:

create table 表名(

列名1 数据类型 primary key auto_increment,

...

)auto_increment=数值;

创建表后指定自增长字段初始值:

create table 表名(

列名1 数据类型 primary key auto_increment,

...

);

alter table 表名 auto_increment=数值;

delete 数据后,自动增长从断点继续增长

turncate 数据后自动增长从默认起始值开始

4.非空约束

(1)创建表时指定的约束

create table 表名 (

字段名 类型 not null,

字段名 类型

);

(2)创建表之后修改建立约束

alter table 表名 madify 字段名 类型 not null;

(3)删除非空约束

alter table 表名 modify 字段名 类型;

5.唯一约束

(1)创建表时

create table 表名 (

....

字段名 类型 unique

);

(2)创建表之后

alter table 表名 add constraint unique_pn(唯一约束名) unique(列名);

-----unique_pn 是唯一约束名

在MySQL中NULL和任何值都不相等(包括他自己)

(3)删除唯一约束

alter table 表名 drop index unique_pn(唯一约束名)

6.默认约束

(1)在创建时设置默认值

create table 表名(

字段名 类型 default 默认值

);

(2)创建后指定默认值

alter table 表名 modify 列名 类型 default 默认值;

(3)删除默认约束

alter table 表名 modify 列名 类型 default null;

 

评论 186
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小唐同学爱学习

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值