约束

常见约束

  1、not  null:非空

    该字段的值是必填,不能为空

  2、default:默认

    该字段有默认值

  3、primary  key:主键

    该字段值不可以重复

  4、unique:唯一约束

    该字段值不可以重复

  5、foreign  key:外键

    用于限制多表的关系

列级约束:

  语法:

    create  table  表名(

    字段名  字段类型  列级约束,

    字段名  字段类型  列级约束,

    )

  例:

    

create  table  表名(

    字段1  字段类型  primary  key,

    字段2  字段类型  not  null,

    字段3  字段类型  default  ‘默认值’,

    字段4  字段类型  unique,

    );

表级约束:

  语法:

    create  table  表名(

    字段名  字段类型,

    字段名  字段类型,

    constarint  约束名  约束类型  字段,

    constarint  约束名  约束类型  字段,

    ......

    );

修改表时添加约束:

  1、添加非空

    alter  table  表名  modify  column  字段名  字段类型  not  null;

  2、添加默认

    alter  table  表名  modify  column  字段名  字段类型  default  '默认值';

  3、添加主键

    方法一:

      alter  table  表名  modify  column  字段名  字段类型  primary  key;

    方法二:

      alter  table  表名  add  primary  key(字段名);

  4、添加唯一

 

     方法一:

      alter  table  表名  modify  column  字段名  字段类型  unique;

    方法二:

      alter  table  表名  add  constarint  unique(字段名);

  5、添加外键

      alter  table  表名1  add  constarint  约束名  foreign  key  (字段名1)  references  表名2(字段名2);

修改表时除约束: 

  1、删除非空

    alter  table  表名  modify  column  字段名  字段类型;

  2、删除默认

    alter  table  表名  modify  column  字段名  字段类型  unsigned;

 

  3、删除主键

    alter  table  表名  modify  column  字段名  字段类型;

 

      alter  table  表名  drop  primary  key;

  4、删除唯一  

    alter  table  表名  modify  column  字段名  字段类型;

 

  5、删除外键    

      alter  table  表名  drop  foreign  key  约束名;

 

 

 

posted @ 2020-07-24 22:33  ShiQi丶  阅读(130)  评论(0)    收藏  举报