修改数据表
1、修改列定义
ALTER TABLE tbl_name MODIFY [COLUMN] col_name column_definition [FIRST|AFTER col_name]
把id修改到第一行
mysql> ALTER TABLE users3 MODIFY id SMALLINT UNSIGNED NOT NULL FIRST;
Query OK, 0 rows affected (0.36 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> SHOW COLUMNS FROM users3;
+------- - --+--------------------- -+---- --+--- --+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------- -- -+---------------------- +----- -+--- --+---------+-------+
| id | smallint(5) unsigned | NO | | NULL | |
| username | varchar(10) | NO | | NULL | |
| pid | smallint(5) unsigned | YES | | NULL | |
| age | tinyint(3) unsigned | NO | | NULL | |
+------ -- --+----------------------+------+-----+---------+-------+
4 rows in set (0.01 sec)
修改列定义时有可能会造成数据丢失,例id类型由smallint改为tinyint.
2、修改列名称(CHANGE [COLUMN]既可以修改列定义,也可以修改列名称)
ALTER TABLE tbl_name CHANGE [COLUMN] old_col_nmae new_col_name column_definition [FIRST|AFTER col_name]
mysql> ALTER TABLE users3 CHANGE pid p_id TINYINT UNSIGNED NOT NULL;
Query OK, 0 rows affected (0.23 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> SHOW COLUMNS FROM users3;
+------- - --+--------------------- -+---- --+--- --+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------- -- -+---------------------- +----- -+--- --+---------+-------+
| id | smallint(5) unsigned | NO | | NULL | |
| username | varchar(10) | NO | | NULL | |
| pid |tinyint(5) unsigned |NO | | NULL | |
| age | tinyint(3) unsigned | NO | | NULL | |
+------ -- --+----------------------+------+-----+---------+-------+
4 rows in set (0.01 sec)
3、修改数据表的名称
第一种方法:ALTER TABLE tbl_name RENAME [TO|AS] new_tbl_name
第二种方法:RENAME TABLE tbl_name TO new_tbl_name [tbl2_name TO new_tbl2_name]
mysql> ALTER TABLE users3 RENAME USERS4;
Query OK, 0 rows affected (0.06 sec)
mysql> SHOW TABLES;
+----------------+
| Tables_in_test |
+----------------+
| province |
| users |
| users1 |
| users2 |
| users4 |
+----------------+
5 rows in set (0.00 sec)
mysql> RENAME TABLE users4 TO users3;
Query OK, 0 rows affected (0.11 sec)
mysql> SHOW TABLES;
+----------------+
| Tables_in_test |
+----------------+
| province |
| users |
| users1 |
| users2 |
| users3 |
+----------------+
建议尽量少使用数据列的更名和数据表的更名