mysql实例之使用alter table命令修改表结构
mysql alter table语句可以修改表的基本结构,例如添加字段、删除字段、添加主键、添加索引、修改字段数据类型、对表重命名等等操作,本文章通过两个简单的实例向大家介绍mysql alter table的使用方法
实例一:使用ALTER TABLE命令向表中添加字段、修改字段类型以及设置主键。
首先创建一个表,SQL语句如下:
mysql> CREATE TABLE myTable(
-> ID SMALLINT
-> );
使用desc命令查看表结构:
mysql> desc myTable;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| ID | smallint(6) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
使用ALTER TABLE命令向表中添加字段、修改字段类型以及设置主键,SQL语句如下:
mysql> ALTER TABLE myTable
-> ADD COLUMN Quantity SMALLINT UNSIGNED NOT NULL,
-> MODIFY ID SMALLINT UNSIGNED NOT NULL,
-> ADD PRIMARY KEY (ID);
再次使用desc命令查看表结构,我们发现上面的修改命令生效了:
desc myTable;
+----------+----------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+----------------------+------+-----+---------+-------+
| ID | smallint(5) unsigned | NO | PRI | | |
| Quantity | smallint(5) unsigned | NO | | | |
+----------+----------------------+------+-----+---------+-------+
实例二:在上面的实例基础上,我们删除myTable表中的Quantity字段和PRIMARY KEY主键
mysql> ALTER TABLE myTable
-> DROP COLUMN Quantity,
-> DROP PRIMARY KEY;
查看表结构:
mysql> desc myTable;
+-------+----------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------------------+------+-----+---------+-------+
| ID | smallint(5) unsigned | NO | | | |
+-------+----------------------+------+-----+---------+-------+
感谢阅读此文,希望能帮助到大家,谢谢大家对本站的支持!