咱们应用alter table add column语句向现有表中增加新列。
简介
alter table table_nameadd [column] column_name column_definition [first|after existing_column];阐明:
alter table子句后指定表名;column关键字是可选的,能够省略它;- 能够通过
first关键字将新列增加为表的第一列,也能够应用after existing_column子句在现有列之后增加新列,如果没有明确指定会将其增加为最初一列;
若要向表中增加两个或更多列,应用上面语法:
alter table table_nameadd [column] column_name column_definition [first|after existing_column],add [column] column_name column_definition [first|after existing_column],...;举例
创立一个表
create database test;use test;create table if not exists vendor ( id int auto_increment primary key, name varchar(255));增加新列并指定地位
alter table vendoradd column phone varchar(15) after name;增加新列但不指定新列地位
alter table vendoradd column vendor_group int not null;插入记录
insert into vendor(name, phone, vendor_group)values('IBM', '(408)-298-2987', 1);insert into vendor(name, phone, vendor_group)values('Microsoft', '(408)-298-2988', 1);同时增加两列
alter table vendoradd column email varchar(100) not null,add column hourly_rate decimal(10, 2) not null;留神:email和hourly_rate两列都是not null,然而vendor表曾经有数据了,在这种状况下,MySQL将应用这些新列的默认值。
查看vendor表中的数据
select id, name, phone, vendor_group, email, hourly_ratefrom 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将产生谬误
alter table vendoradd column vendor_group int not null;操作后果:
ERROR 1060 (42S21): Duplicate column name 'vendor_group'检查表中是否已存在列
对于几列的表,很容易看到哪些列曾经存在,如果有一个饮食数百列的大表,那就比拟吃力了
select if(count(*) = 1, 'Exist', 'Not Exist') as resultfrom information_schema.columnswhere table_schema = 'test' and table_name = 'vendor' and column_name = 'phone';查问后果:
+--------+| result |+--------+| Exist |+--------+1 row in set (0.00 sec)在where子句中,咱们传递了三个参数:表模式或数据库,表名和列名。咱们应用if函数来返回列是否存在。
参考
https://www.begtut.com/mysql/...