mysql如何修改表结构(alter table),多列/多字段

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

mysql如何修改表结构(alter table),多列/多字段

苦笔   2022-12-24 我要评论

mysql修改表结构(alter table),多列/多字段

--创建测试表
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);		--正确
--name关键字作为字段名,重命名需要加反引号(`)
alter table table_name change `name` field_name varchar(50);

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);	--错误

mysql alter table修改表结构添加多个字段的几个写法

如题目,本文介绍mysql中,add column添加多字段的几个写法。

分开写多个 alter table

听起来好像是多此一举的介绍,有时需要给相邻字段不同的修改,全都分开写,也不失为不容易出错的写法。

ALTER TABLE employee ADD email_address varchar(50);

ALTER TABLE employee MODIFY address varchar(30);

ALTER TABLE employee ADD COLUMN last_name varchar(30);

合并写在一起

具体看下面的例子,这几种写法都可以。

可以不带column关键字。

-- 创建测试表

create table test_alter (id int);

-- 只写add,没有 column 关键字, 增加的多个字段内容在大括号中

alter table test_alter add (user_name char(5), address varchar(30));

-- 带 column 关键字, 增加的多个字段内容在大括号中

alter table test_alter add column (user_name char(5), address varchar(30));

-- 分开写多个add,没有 column 关键字, 没有大括号

alter table test_alter add user_name char(5), add address varchar(30);

-- 分开写多个add,带有 column 关键字, 没有大括号

alter table test_alter add column user_name char(5), add column address varchar(30);

-- 小扩展,分开写多个除了写add,也可以写modify等其他修改

alter table test_alter add user_name char(5), modify address varchar(15);

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们