mysql alter操作总结(修改表名,表结构,字段,索引,主键等)

为了清晰的理解和记忆mysql的alter操作,现在做一下简单的总结,希望对您有所帮助。

本文涉及到的原始表:

DROP TABLE IF EXISTS mysql_test;
CREATE TABLE mysql_test(
  `id` bigint UNSIGNED NOT NULL AUTO_INCREMENT,
  `report_date` date NOT NULL,
  `cam` varchar(32) NOT NULL DEFAULT '0',
  `bud_value` float NOT NULL DEFAULT '0.0000',
  `b_value` float NOT NULL DEFAULT '0.0000',
  `cost` float NOT NULL DEFAULT '0.0000',
  `status` varchar(16) NOT NULL DEFAULT '',
  `utime` timestamp,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uid` (`report_date`,`cam`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

1.修改表名

将表名mysql_test 改成test_ai

sql语句如下:

alter table test_ai rename mysql_test;

2.表结构修改

添加字段test_add:

alter table test_ai add test_add varchar(10) NOT NULL DEFAULT '';

添加aaa字段在status后面:

alter table test_ai add aaa varchar(10) NOT NULL DEFAULT '' after status;

或者:

alter table test_ai add column aaa varchar(10) NOT NULL DEFAULT '' after status;

删除cam字段:

alter table test_ai drop b_value;

修改字段名称/类型:

alter table test_ai change aaa test_aaa int(10) unsigned NOT NULL DEFAULT 0;

移动表中字段的位置(将bud_value字段移动到b_value字段后面):

alter table test_ai modify bud_value float after b_value;

修改自增长的起始值:

alter table test_ai auto_increment=1000;

3.索引修改

查看索引test_ai表的索引:

show index from test_ai;

创建索引 index_u和index_uu:

 create index index_u on test_ai (report_date, cost, status);

或者:

ALTER TABLE test_ai ADD INDEX index_uu (report_date, cost, status);

删除索引:

ALTER TABLE test_ai DROP INDEX index_u;

或者:

DROP index index_uu ON test_ai;

添加主键索引 key_uid:

ALTER TABLE test_ai ADD UNIQUE KEY `key_uid` (`report_date`,`cost`);

删除自增长id:

 alter table test_ai change id id int;

删除主键:

alter table test_ai drop primary key;

添加primary key:

ALTER TABLE test_ai ADD PRIMARY KEY (cam);

修改字段为自增长类型:

alter table test_ai change id id int primary key auto_increment;

4.字段备注修改

修改cost的备注信息为:“消耗信息”:

alter table test_ai change cost cost float NOT NULL DEFAULT '0.0000' comment '消耗信息';

特别提醒:

在编写存储过程或者sql的时候,注意不要出现Tab键,统一将Tab键,替换为4个空格。Tab键在linux系统中可以无法识别。

猜你喜欢

转载自blog.csdn.net/adayan_2015/article/details/82782865