最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

歡迎光臨散文網(wǎng) 會(huì)員登陸 & 注冊(cè)

MySQL向表中添加列

2022-10-27 21:04 作者:限量版范兒  | 我要投稿

我們使用alter table add column語(yǔ)句向現(xiàn)有表中添加新列。

簡(jiǎn)介

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

說(shuō)明:

  • alter table子句后指定表名;

  • column關(guān)鍵字是可選的,可以省略它;

  • 可以通過(guò)first關(guān)鍵字將新列添加為表的第一列,也可以使用after existing_column子句在現(xiàn)有列之后添加新列,如果沒(méi)有明確指定會(huì)將其添加為最后一列;

若要向表中添加兩個(gè)或更多列,使用下面語(yǔ)法:

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

舉例

創(chuàng)建一個(gè)表

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

同時(shí)添加兩列

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表已經(jīng)有數(shù)據(jù)了,在這種情況下,MySQL將使用這些新列的默認(rèn)值。

檢查vendor表中的數(shù)據(jù)

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

查詢結(jié)果:

+----+-----------+----------------+--------------+-------+-------------+ | 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將發(fā)生錯(cuò)誤

alter table vendor add column vendor_group int not null;

操作結(jié)果:

ERROR 1060 (42S21): Duplicate column name 'vendor_group'

檢查表中是否已存在列

對(duì)于幾列的表,很容易看到哪些列已經(jīng)存在,如果有一個(gè)飲食數(shù)百列的大表,那就比較費(fèi)勁了

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';

查詢結(jié)果:

+--------+ | result | +--------+ | Exist ?| +--------+ 1 row in set (0.00 sec)

在where子句中,我們傳遞了三個(gè)參數(shù):表模式或數(shù)據(jù)庫(kù),表名和列名。我們使用if函數(shù)來(lái)返回列是否存在。

鏈接:https://www.dianjilingqu.com/589058.html


MySQL向表中添加列的評(píng)論 (共 條)

分享到微博請(qǐng)遵守國(guó)家法律
隆回县| 漯河市| 奎屯市| 宣化县| 阳谷县| 苏尼特右旗| 兰溪市| 黑河市| 万年县| 蓬溪县| 喀喇沁旗| 阿拉善盟| 万载县| 崇左市| 桐庐县| 万安县| 宁乡县| 平山县| 洪雅县| 罗源县| 南平市| 沂水县| 嘉义市| 六安市| 平阴县| 永福县| 平果县| 都安| 灌云县| 霍林郭勒市| 岳西县| 阜宁县| 昭通市| 敦煌市| 辽阳县| 海宁市| 清河县| 武冈市| 楚雄市| 尼木县| 辽源市|