記錄一些簡單的表的管理知識,友善使用!
mysql> desc yql9;
+-------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
| id | int(11) | YES | | NULL | |
| val | char(5) | YES | | NULL | |
2 rows in set (0.00 sec)
1 添加字段 ALTER TABLE tabname ADD field_name field_type;
mysql> alter table yql9 add new_id int(5) unsigned default 0 not null auto_increment ,add primary key (new_id);
ERROR 1067 (42000): Invalid default value for 'new_id'
mysql> alter table yql9 add new_id int(5) unsigned not null auto_increment ,add primary key (new_id);
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> alter table yql9 add gmt_created timestamp;
mysql> desc yql9;
+-------------+-----------------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
| id | int(11) | YES | | NULL | |
| val | char(5) | YES | | NULL | |
| new_id | int(5) unsigned | NO | PRI | NULL | auto_increment |
| gmt_created | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
4 rows in set (0.01 sec)
2 删除字段 alter table tabname drop field_name;
mysql> alter table yql9 drop column new_id;
Query OK, 0 rows affected (0.01 sec)
+-------------+-----------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
| id | int(11) | YES | | NULL | |
| val | char(5) | YES | | NULL | |
| gmt_created | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
3 rows in set (0.00 sec)
mysql> alter table yangql9 drop v;
mysql> desc yangql9;
| id | int(11) | NO | PRI | 0 | |
3 修改字段的資料類型 alter table tabname change old_field_name new_field_name field_type;
mysql> alter table yql9 change val v integer;
| v | int(11) | YES | | NULL | |
mysql> alter table yql9 change v v tinyint not null default 0;
+-------------+------------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
| id | int(11) | YES | | NULL | |
| v | tinyint(4) | NO | | 0 | |
| gmt_created | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
4 重命名表
mysql> alter table yql9 rename yangql9;
5 添加索引 alter table tabname add index /create index idxname on tabname(column_name);
mysql> alter table yangql9 add index id_idx (id);
Query OK, 0 rows affected (0.03 sec)
| id | int(11) | YES | MUL | NULL | |
6 添加主鍵
mysql> alter table yangql9 add primary key(id);
| id | int(11) | NO | PRI | 0 | |