ALTER TABLE vendors
ADD COLUMN vendor_group INT NOT NULL;
让我们插入一些行数据到vendors表。
INSERT INTO vendors(name,phone,vendor_group)
VALUES('IBM','(408)-298-2987',1);
INSERT INTO vendors(name,phone,vendor_group)
VALUES('Microsoft','(408)-298-2988',1);
SELECT
id, name, phone, vendor_group, email, hourly_rate
FROM
vendors;
+----+-----------+----------------+--------------+-------+-------------+
| id | name | phone | vendor_group | email | hourly_rate |
+----+-----------+----------------+--------------+-------+-------------+
| 1 | IBM | (408)-298-2987 | 1 | | 0 |
| 2 | Microsoft | (408)-298-2988 | 1 | | 0 |
+----+-----------+----------------+--------------+-------+-------------+
2 rows in set
email列填充有空白字符值,而不是NULL值。hourly_rate列填充0.00值。
如果不小心添加了表中已经存在的列,MySQL将发出错误。 例如,如果执行以下语句:
ALTER TABLE vendors
ADD COLUMN vendor_group INT NOT NULL;
MySQL发出错误消息:
Error Code: 1060. Duplicate column name 'vendor_group'
对于具有几列的表,很容易看出哪些列已经存在。 但是,有一个大表中有一百个列,这是比较困难的。
在某些情况下,您需要在添加表之前检查一列是否已经存在。 但是,没有像ADD COLUMN IF NOT EXISTS这样的声明。 但是可以从information_schema数据库的columns表中获取以下信息:
SELECT
IF(count(*) = 1, 'Exist','Not Exist') AS result
FROM
information_schema.columns
WHERE
table_schema = 'testdb'
AND table_name = 'vendors'
AND column_name = 'phone';
+--------+
| result |
+--------+
| Exist |
+--------+
1 row in set