码迷,mamicode.com
首页 > 其他好文 > 详细

小白之旅20

时间:2019-08-09 21:39:44      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:值类型   index   更新   数值类型   完整   enc   modify   自增   小白   

约束

概念:对表中的数据进行限制,保证数据的正确性、完整性、有效性

一. 主键约束 primary key

  • 特点:
    • 非空、唯一,是表中记录的唯一标识
    • 一张表只能有一个主键
  • 建表时,添加主键
    • create table emp (eid varchar(20) primary key , ename varchar(20) , eage int , ...); 建议将主键放在第一位
    • create table emp (eid varchar(20) , ename varchar(20) , eage int , ... , primary key (eid));
  • 删除主键
    • 不能使用修改列类型的方式删除主键, 即:alter table emp modify eid varchar(20);
    • alter table emp drop primary key; 注:只删除了唯一约束
  • 建表后,设置主键
    • alter table emp modify eid varchar(20) primary key;
  • 主键自增长:数值类型的主键,可以通过 auto_increment 使主键自动增长,只有主键能自增长,auto_increment 也是MySQL的方言
    • 建表时,添加主键自增长
      • create table emp (eid int primary key auto_increment , ename varchar(20) , ... );
    • 建表后,设置主键自增长
      • alter table emp modify eid int auto_increment;
    • 删除自增长
      • alter table emp modify eid int;

注:

1、自增长的类型必须是数值类型的

2、小数类型也能自增长,例如:2.3 的下一个自增长是 3

3、在对主键进行增删时,必须要保证前后操作的数据是正确的

二. 非空约束 not null

  • 建表时,添加非空约束
    • create table emp (eid int , ename varchar(20) not null , eage int , ...);
  • 建表后,添加非空约束
    • alter table emp modify eage int not null;
  • 删除非空约束
    • alter table emp modify eaddr varchar(50);

三. 唯一约束 unique

  • 建表时,添加唯一约束
    • create table emp (eid int unique , ename varchar(20) , ...);
  • 建表后,添加唯一约束
    • alter table emp modify eage int unique;
  • 删除唯一约束
    • alter table emp drop index eage;

四,外键约束 foreign key

用于保证数据的完整性

  • 建表时,添加外键
    • create table 表名 ( 主键字段 类型 约束,字段 类型 [约束],... ,外键字段 类型 , constraint 外键名称 foreign key (外键字段) references 主表(主表主键));
    • create table 表名 ( 主键字段 类型 约束,字段 类型 [约束],... ,外键字段 类型 , foreign key (外键字段) references 主表(主表主键));
  • 删除外键
    • altert table 表名 drop foreign key 外键名称;
  • 建表后,添加外键
    • alter table 表名 add constraint 外键名称 foreign key(外键字段) references 主表(主表主键);
    • alter table 表名 add foreign key(外键字段) references 主表(主表主键);

补充:级联操作

添加级联功能

  • alter table 表名 add foreign key(外键字段) references 主表(主表主键) on delete cascade; -- 动态删除
  • alter table 表名 add foreign key(外键字段) references 主表(主表主键) on update cascade; -- 动态更新

1、级联删除:on delete cascade

2、级联更新:on update cascade

小白之旅20

标签:值类型   index   更新   数值类型   完整   enc   modify   自增   小白   

原文地址:https://www.cnblogs.com/demonycw/p/11329505.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!