mysql知识点5(修改表)

修改表的语法

一张表创建完毕,有了N列之后还有可能要增加或删除或修改列
添加字段
    Alter table 表名 add 列名称 列类型 列参数 
    例如:Alter table lvshihao add name varchar(255);
    Alter table 表名 add 列名称 列类型 列参数 after 指定列[后面]
    例如:Alter table lvshihao add age int(10) after password;
    Alter table 表名 add 列名称 列类型 列参数 first 添加到首位
    例如:Alter table lvshihao add age int(10) first;
    可以一次性添加多个如
    Alter table lvshihao add name varchar(255),add age int;
删除字段
    Alter table 表名 drop 列名称
    例如:Alter table lvshihao drop name;
    可以一次性删除多个如
    Alter table lvshihao drop name,drop age;
修改字段
    Alter table 表名 modify 列名称 新类型 新参数 [FIRST|AFTER 字段名称](不能修改列名称)
    例如:Alter table lvshihao modify name varchar(455);
修改字段名称
    Alter table 表名 change 旧列名称 新列名 新类型 新参数 [FIRST|AFTER 字段名称]
    例如:Alter table lvshihao change name names int;
添加默认值
    Alter table 表名 Alter 字段名 SET DEFAULT 默认值;
删除默认值
    alter table 表名 alter 字段名 drop default;
添加主键
    alter table 表名 add [constraint [symbol]] primary key [index_type](字段名称,..);
    alter table 表名 add primary key(id,card);
    alter table 表名 add constraint symbol primary key index_type(id);
删除主键
    alter table 表名 drop primary key;
    (注意:在删除一个字段主键的时候,如果此字段是自增长的话应该首先去掉自增长)
    去掉自增长可以使用,下面虽然不能去掉主键,但是可以去掉主键以外的属性
    alter table 表名 modify id int unsigned;
添加唯一
    alter table 表名 add [constraint [symbol]] unique [index|key] [索引名称] (字段名称,...) 
删除唯一
    alter table 表名 drop {index|key} 索引名称
修改表的存储引擎
    alter table 表名 engine=存储引擎名称
设置自增长的值
    alter table 表名 auto_increment=值(下次插入值,只要不指定自增字段的值,那么下次就是100)
删除外键
    ALTER TABLE employee drop foreign key emp_fk_dep;
添加外键
    ALTER TABLE employee add constraint emp_fk_dep foreign key(depId) references department(id);

注意

如果类型改变了,导致数据储蓄不了怎么办?
如int改成smalint列 如果不匹配数据将会丢失或者在mysql的strict_mode下,修改不了。

转载于:https://www.cnblogs.com/lvshihao/articles/11065880.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值