MySQL向表中添加列

打印 上一主题 下一主题

主题 896|帖子 896|积分 2688

我们使用alter table add column语句向现有表中添加新列。
简介
  1. alter table table_name
  2. add [column] column_name column_definition [first|after existing_column];
复制代码
说明:

  • alter table子句后指定表名;
  • column关键字是可选的,可以省略它;
  • 可以通过first关键字将新列添加为表的第一列,也可以使用after existing_column子句在现有列之后添加新列,如果没有明确指定会将其添加为最后一列;
若要向表中添加两个或更多列,使用下面语法:
  1. alter table table_name
  2. add [column] column_name column_definition [first|after existing_column],
  3. add [column] column_name column_definition [first|after existing_column],
  4. ...;
复制代码
举例

创建一个表
  1. create database test;
  2. use test;
  3. create table if not exists vendor (
  4.         id int auto_increment primary key,
  5.   name varchar(255)
  6. );
复制代码
添加新列并指定位置
  1. alter table vendor
  2. add column phone varchar(15) after name;
复制代码
添加新列但不指定新列位置
  1. alter table vendor
  2. add column vendor_group int not null;
复制代码
插入记录
  1. insert into vendor(name, phone, vendor_group)
  2. values('IBM', '(408)-298-2987', 1);
  3. insert into vendor(name, phone, vendor_group)
  4. values('Microsoft', '(408)-298-2988', 1);
复制代码
同时添加两列
  1. alter table vendor
  2. add column email varchar(100) not null,
  3. add column hourly_rate decimal(10, 2) not null;
复制代码
注意:email和hourly_rate两列都是not null,但是vendor表已经有数据了,在这种情况下,MySQL将使用这些新列的默认值。
检查vendor表中的数据
  1. select id, name, phone, vendor_group, email, hourly_rate
  2. from vendor;
复制代码
查询结果:
  1. +----+-----------+----------------+--------------+-------+-------------+
  2. | id | name      | phone          | vendor_group | email | hourly_rate |
  3. +----+-----------+----------------+--------------+-------+-------------+
  4. |  1 | IBM       | (408)-298-2987 |            1 |       |        0.00 |
  5. |  2 | Microsoft | (408)-298-2988 |            1 |       |        0.00 |
  6. +----+-----------+----------------+--------------+-------+-------------+
  7. 2 rows in set (0.00 sec)
复制代码
email列中填充了空值,而不是NULL值,hourly_rate列填充了0.00
添加表中已存在的列

MySQL将发生错误
  1. alter table vendor
  2. add column vendor_group int not null;
复制代码
操作结果:
  1. ERROR 1060 (42S21): Duplicate column name 'vendor_group'
复制代码
检查表中是否已存在列

对于几列的表,很容易看到哪些列已经存在,如果有一个饮食数百列的大表,那就比较费劲了
  1. select if(count(*) = 1, 'Exist', 'Not Exist') as result
  2. from information_schema.columns
  3. where table_schema = 'test'
  4.         and table_name = 'vendor'
  5.         and column_name = 'phone';
复制代码
查询结果:
  1. +--------+
  2. | result |
  3. +--------+
  4. | Exist  |
  5. +--------+
  6. 1 row in set (0.00 sec)
复制代码
在where子句中,我们传递了三个参数:表模式或数据库,表名和列名。我们使用if函数来返回列是否存在。
参考

https://www.begtut.com/mysql/mysql-add-column.html

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

科技颠覆者

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表