alter语法

博客分类: mysql 阅读次数: comments

alter语法

批量操作

--创建测试表
create table test(
    id int;
);
--add支持多列,change/drop需要在每列前添加关键字,逗号隔开,'column'可有可无
--添加多列
alter table test add (c1 char(1),c2 char(1));   --正确,add支持多列
alter table test add column (c1 char(1),c2 char(1));    --正确
alter table test add c1 char(1),add c2 char(1);     --正确
--修改多列
alter table test change c1 c3 char(1),change c2 c4 char(1);     --正确
alter table test change column c1 c3 char(1),change column c2 c4 char(1);       --正确
alter table test change (c1 c3 char(1),c2 c4 char(1));      --错误
--删除多列
alter table test drop c1,drop c2;   --正确
alter table test drop column c1,drop column c2;     --正确
alter table test drop c1,c2;    --错误
alter table test drop (c1,c2);  --错误

增加一个字段

alter table user add COLUMN new1 VARCHAR(20) DEFAULT NULL; 
alter table user add COLUMN new2 VARCHAR(20) NOT NULL;

批量怎加字段

bagin;                                           //事务开始
alter table em_day_data add f_day_house7 int(11);
alter table em_day_data add f_day_house8 int(11);
alter table em_day_data add f_day_house9 int(11);
alter table em_day_data add f_day_house10 int(11);
commit;                                             //提交事务,事务结束
alter table em_day_data add (f_day_house11 int(11),f_day_house12 int(11),f_day_house13 int(11));  

删除一个字段

alter table user DROP COLUMN new2;

修改一个字段

//修改一个字段的类型
alter table user MODIFY new1 VARCHAR(10);
//修改一个字段的名称,此时一定要重新指定该字段的类型
alter table user CHANGE new1 new4 int;

批量修改

alter table 表 change 修改前字段名  修改后字段名称 int(11) not null,
change 修改前字段名  修改后字段名称 int(11) not null,
change 修改前字段名  修改后字段名称 int(11) not null,
change 修改前字段名  修改后字段名称 int(11) not null,
change 修改前字段名  修改后字段名称 int(11) not null

修改字段属性

-- ALTER TABLE tb_name MODIFY 字段名称 字段类型 [完整性约束条件]
-- 将email字段 VARCHAR(50)修改成VARCHAR(200)
-- 注意,修改时如果不带完整性约束条件,原有的约束条件将丢失,如果想保留修改时就得带上完整性约束条件
ALTER TABLE user10 MODIFY email VARCHAR(200) NOT NULL DEFAULT 'a@a.com';
-- 将card移到test后面
ALTER TABLE user10 MODIFY card CHAR(10) AFTER test;
-- 将test放到第一个,保留原完整性约束条件
ALTER TABLE user10 MODIFY test CHAR(32) NOT NULL DEFAULT '123' FIRST;

--修改多列,添加,修改
ALTER TABLE `table` 
add(
    `ids` text COLLATE utf8_unicode_ci COMMENT '',
    `prs` text COLLATE utf8_unicode_ci COMMENT ''
) , 
MODIFY COLUMN  `ids` text COLLATE utf8_unicode_ci COMMENT '',
ALTER COLUMN `type` SET DEFAULT '0',
ALTER COLUMN `error_num` SET DEFAULT '0',
ALTER COLUMN `success_num` SET DEFAULT '0',
ALTER COLUMN `all_num` SET DEFAULT '0';