数据库关于修改表的一些只是总结

发表于:2014-1-13 10:22

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:samlee1993    来源:51Testing软件测试网采编

  在我们设计数据库的时候,难免会有需要修改的地方,今天我就把自己学习的关于数据库的表修改的一些知识做一个总结。
  对于每一个知识点我会举一个例子,我以一个名为test的表举例,test里面包含的列有id,name,age,content,这样可以帮助我们更好的理解这些知识。
  1 修改列的数据类型
  alter table test modify name varchar (30);
  2 追加新列
  alter table test add sex char(2);
  3 改变列的位置
  alter table test modify content after name;
  4 改变列名和类型
  alter table test change age old tinyint;
  5 删除列
  alter table test drop sex;
  6 删除表
  drop table test;
  7 表的列构造+数据的复制
  create table test2 select * from test;
  8 复制列构造
  create table test3 like test;
  9 数据的复制
  insert into test3 select * from test;
  10 在修改表时添加主键约束
  alter table test add constraint pk primary key (id);
  11 在修改表示删除主键约束
  alter table test drop primary key;
  12 在修改表示添加外键约束
  alter table test add constraint fk foreign key (id) references test2 (id);
  13 在修改表时删除外键约束
  alter table test drop foreign key fk;注:fk为外键名称
  14 在修改表时添加默认值约束
  alter table test alter sex set default ‘f’;
  15 在修改表时删除默认值约束
  alter table test alter sex drop default;
  16 在修改表时添加非空约束
  alter table test modify name varchar(20) not null;
  注:在mysql数据库中,非空约束是不能删除的,但是可以将设置成not null的列修改成null,实际也就相当于取消了非空约束。
  17 在修改表时添加检查约束
  alter table test add constraint checkname check(age>19);
  在mysql中,就算添加检查约束,但还是可以加入不合法数据
  18  在修改表是添加一个唯一约束
  alter table test add constraint uq unique(name);
  19 在修改表时删除唯一约束
  drop index uq on test;
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号