0


MySQL向表中添加列

我们使用

alter table add column

语句向现有表中添加新列。

简介

altertable table_name
add[column] column_name column_definition [first|after existing_column];

说明:

  • alter table子句后指定表名;
  • column关键字是可选的,可以省略它;
  • 可以通过first关键字将新列添加为表的第一列,也可以使用after existing_column子句在现有列之后添加新列,如果没有明确指定会将其添加为最后一列;

若要向表中添加两个或更多列,使用下面语法:

altertable table_name
add[column] column_name column_definition [first|after existing_column],add[column] column_name column_definition [first|after existing_column],...;

举例

创建一个表

createdatabase test;use test;createtableifnotexists vendor (
    id intauto_incrementprimarykey,
  name varchar(255));

添加新列并指定位置

altertable vendor
addcolumn phone varchar(15)after name;

添加新列但不指定新列位置

altertable vendor
addcolumn vendor_group intnotnull;

插入记录

insertinto vendor(name, phone, vendor_group)values('IBM','(408)-298-2987',1);insertinto vendor(name, phone, vendor_group)values('Microsoft','(408)-298-2988',1);

同时添加两列

altertable vendor
addcolumn email varchar(100)notnull,addcolumn hourly_rate decimal(10,2)notnull;

注意:email和hourly_rate两列都是not null,但是vendor表已经有数据了,在这种情况下,MySQL将使用这些新列的默认值。

检查vendor表中的数据

select id, name, phone, vendor_group, email, hourly_rate
from vendor;

查询结果:

+----+-----------+----------------+--------------+-------+-------------+
| id | name      | phone          | vendor_group | email | hourly_rate |
+----+-----------+----------------+--------------+-------+-------------+
|  1 | IBM       | (408)-298-2987 |            1 |       |        0.00 |
|  2 | Microsoft | (408)-298-2988 |            1 |       |        0.00 |
+----+-----------+----------------+--------------+-------+-------------+
2 rows in set (0.00 sec)

email列中填充了空值,而不是NULL值,hourly_rate列填充了0.00

添加表中已存在的列

MySQL将发生错误

altertable vendor
addcolumn vendor_group intnotnull;

操作结果:

ERROR 1060(42S21): Duplicatecolumn name 'vendor_group'

检查表中是否已存在列

对于几列的表,很容易看到哪些列已经存在,如果有一个饮食数百列的大表,那就比较费劲了

selectif(count(*)=1,'Exist','Not Exist')as result
from information_schema.columnswhere table_schema ='test'and table_name ='vendor'and column_name ='phone';

查询结果:

+--------+| result |+--------+| Exist  |+--------+1rowinset(0.00 sec)

在where子句中,我们传递了三个参数:表模式或数据库,表名和列名。我们使用if函数来返回列是否存在。

参考

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

标签: mysql 数据库

本文转载自: https://blog.csdn.net/ln_ydc/article/details/127560296
版权归原作者 okokabcd 所有, 如有侵权,请联系我们删除。

“MySQL向表中添加列”的评论:

还没有评论