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 | | | | +-------+----------------------+------+-----+---------+-------+
感謝閱讀此文,希望能幫助到大家,謝謝大家對本站的支持!