关于数据库修改表的一些个人总结

在我们设计数据库的时候,难免会有需要修改的地方,今天我就把自己学习的关于数据库的表修改的一些知识做一个总结。
  对于每一个知识点我会举一个例子,我以一个名为 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;

猜你喜欢

转载自shinepaopao.iteye.com/blog/2004093