mysql约束基础系列二

1.主键约束(alter … modify/change … / alter … add primary key …)  
    添加
        alter table 表名 add primary key(字段)
        alter table 表名 add constraint pk_表名_字段名 primary key(id, name);
        alter table 表名 modify 字段 数据类型 primary key
        alter table 表名 change 字段1 字段2 数据类型 primary key
    删除
        alter table 表名 drop primary key;
        注意:如果删除的主键约束具有自增长约束,则必须先删除自增长约束,再去删除主键约束。    

2.外键约束(慎用)
    添加
        alter table 表名 add constraint 约束名 foreign key(外键列) references 主键表(主键列)
    删除
        第一步:删除外键
        alter table 表名 drop foreign key 约束名
        第二步:删除索引
        alter  table 表名 drop  index 索引名 
        约束名和索引名一样
        
    注意
        在创建表时,不去明确指定外键约束的名称,系统会自动地生成一个外键的名称。
        使用 show create table 表名 查看具体的外键名称
        
    设置外键中的级联关系
        on delete cascade: 删除主表中的数据时,从表中的数据随之删除
        on update cascase: 更新主表中的数据时,从表中的数据随之更新
        on delete set null: 删除主表中的数据时,从表中的数据置空

    级联删除
        create table emp(
            empno int promary key auto_increment,
            ename varchar(32) not null,
            deptno int,
            [constraint fk_name] foreign key(deptno) references dept(deptno) on delete cascade-- 添加外键约束
        );
        
    注意:
        插入数据时,先插入主表的数据,再插入从表的数据
        删除数据时,先删除从表的数据,再删除主表的数据


3.唯一键约束(alter … modify/change … / alter … add unique)
    添加
        alter table 表名 add unique(字段)
        alter table 表名 add constraint 约束名 unique(字段);
        alter table 表名 modify 字段 数据类型 unique;
        alter table 表名 change 字段1 字段2 数据类型 unique;
    删除
        alter table 表名 drop key 约束名
        alter table 表名 drop index 索引名;        
        注意:如果删除的唯一约束列具有自增长约束,则必须先删除自增长约束,再去删除唯一约束
              默认:约束名=索引名=键名

4.非空约束(alter … modify/change)
    添加
        alter table 表名 modify 字段 数据类型  not null 
        alter table 表名 change 字段1 字段2 数据类型 not null;
    删除
        alter table 表名 modify 字段 数据类型
        alter table 表名 change 字段1 字段2 数据类型;
        
5.自动增长(alter … modify/change)
    添加
        alter table 表名 modify 字段 数据类型  auto_increment
        alter table 表名 change 字段1 字段2 数据类型 auto_increment;
    删除:
        alter table 表名 modify 字段 数据类型;
        alter table 表名 change 字段1 字段2 数据类型;
        注意:一张表只能有一个自增长列,并且该列需要定义约束(there can be only one auto column and it must be defined as a key)。
        
6.默认值(alter … modify/change)
    添加:
        alter table 表名 modify 字段 数据类型 default '值';
        alter table 表名 change 字段1 字段2 数据类型 default '值';
        alter table 表名 alter 字段  set default '值'
    删除:
        alter table 表名 modify 字段 数据类型;
        alter table 表名 change 字段1 字段2 数据类型;
        alter table 表名 alter  字段  drop default

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值