我們使用alter table add column陳述句向現有表中添加新列,
簡介
alter table table_name
add [column] column_name column_definition [first|after existing_column];
說明:
alter table子句后指定表名;column關鍵字是可選的,可以省略它;- 可以通過
first關鍵字將新列添加為表的第一列,也可以使用after existing_column子句在現有列之后添加新列,如果沒有明確指定會將其添加為最后一列;
若要向表中添加兩個或更多列,使用下面語法:
alter table table_name
add [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 vendor
add column phone varchar(15) after name;
添加新列但不指定新列位置
alter table vendor
add 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 vendor
add 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_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將發生錯誤
alter table vendor
add column vendor_group int not null;
操作結果:
ERROR 1060 (42S21): Duplicate column name 'vendor_group'
檢查表中是否已存在列
對于幾列的表,很容易看到哪些列已經存在,如果有一個飲食數百列的大表,那就比較費勁了
select if(count(*) = 1, 'Exist', 'Not Exist') as result
from information_schema.columns
where 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/mysql-add-column.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/521850.html
標籤:其他
上一篇:全球名校AI課程庫(22)| Harvard哈佛 · 計算機科學導論課程『Introduction to Computer Science』
