页次: 1
对于一个创建好的表 ,有时候需要修改表的结构, 也是类似增改删查。
比如增加一列, 删除一列, 增加个索引 等
用一个表做个示例
首先创建一个数据库
http://www.ipbbs.net/viewtopic.php?id=48
创建一个表
mysql> create table ipbbs(id int); Query OK, 0 rows affected (0.11 sec)
现在增加一个列
mysql> alter table ipbbs add name char(20) not null comment 'add name'; Query OK, 0 rows affected (0.14 sec) Records: 0 Duplicates: 0 Warnings: 0
发现,id 太多了, 用过tinyint 就够用了
mysql> alter table ipbbs change id id tinyint ; Query OK, 0 rows affected (0.13 sec) Records: 0 Duplicates: 0 Warnings: 0
这里把id的类型设置为 tinyint 。
change id id tinyint 有两个id , 第一个是原来的id, 第二个就是新的名字。
这样就知道如何修改id这个字段的名字了
mysql> alter table ipbbs change id aid tinyint; Query OK, 0 rows affected (0.11 sec) Records: 0 Duplicates: 0 Warnings: 0
这里后面的 tinyint 是不能省略的了
查看一下目前这个表样子
mysql> desc ipbbs; +-------+------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+------------+------+-----+---------+-------+ | aid | tinyint(4) | YES | | NULL | | | name | char(20) | NO | | NULL | | +-------+------------+------+-----+---------+-------+ 2 rows in set (0.02 sec)
删除一列,感觉有给id就ok, 不要name列了。
mysql> alter table ipbbs drop name; Query OK, 0 rows affected (0.13 sec) Records: 0 Duplicates: 0 Warnings: 0
修改表的名字
mysql> alter table ipbbs rename ipbbs_net; Query OK, 0 rows affected (0.03 sec)
ipbbs.net
离线
页次: 1