Mysql约束

约束

定义:是一种限制,通过对表的行或列的数据做出限制,来确保表的完整性,唯一性。

在MySQL中,常用的几种约束有:

约束类型: 主键 外键 唯一 非空 自增 默认值
关键字: primary key foreign key unique not null auto_increment default

primary key主键


什么是主键:
  • 一个表只能有一个主键,当建表时忘记设置主键约束时.设置为主键的列查询速度会非常快,所以一般会用聚集索引

添加主键约束:

  • create  table 表名(字段名 字段类型 primary key);
    

删除主键约束:

  • alter table myself drop primary key;
    

foreign key


什么是外键:
  • 当建表时需要用到另外一个表的主键作为本表的的主键时,需要设置外键。设置外间后,若想在删除本表数据时会级联删除或者默认删除其他方式。

添加外键约束

  • ##############
    ###创建国家表##
    ##############
    create table state(id int primary key auto_increment,
                      name varchar(20) not null unique
                      );
    ##############
    ###创建学生表##
    ##############                  
    create table student(id int primary key auto_increment,
                         name varchar(16) not null,
                         sex enum('男','女'),
                         state_id int,
                         foreign key(state_id) references state(id)
                         on update cascade
                         on delete cascade
                        );
    
外键联动
  • 级联更新 on update cascade
    级联删除 on delete cascade
    

unique唯一


定义:本列的内容只能唯一不能重复。

添加唯一约束

  • create  table 表名(字段名 字段类型 unique);
    

联合唯一

  • create  table 表名(字段名1 字段类型,字段名2 字段类型,
                    unique(字段名1,字段名2)
                    );
    

not null非空


定义:不为空 - 针对一些字段,如注册时的用户名,出生人的性别等,这些需求下的字段,只不能设置为Null,必须要对其赋值

添加非空约束

  • create  table 表名(字段名 字段类型 unique);
    

auto_increment自增


定义:自增,只能加给key的int类型字段,作为辅助修饰,一个表中只能设置一个自增字段

添加自增约束

create  table 表名(字段名 字段类型 auto_increment);

default默认值


定义:当插入时没有插入值时,会自动插入默认值。默认值约束相对于非空约束而说。

添加默认值

  • alter table 表名 add 列名 列类型 not null default '默认值';
    

清空表

truncate 表名,清空表,并清空主键自增记录

原文地址:https://www.cnblogs.com/ledgua/p/11580087.html