hi,欢迎访问本站!
当前位置: 首页数据库正文

mysql 添加,修改/删除表字段的方法

墨初 数据库 203阅读

mysql添加,修改以及删除数据表中的字段,可以使用下面的命令。

mysql 添加字段的方法

sql命令:

# sql数据表添加新字段命令
alter table [表名] add [字段名] [字段类型] [字段位置]

例:

MariaDB [db_4]> alter table newdatas add age varchar(50);
Query OK, 0 rows affected (0.014 sec)
Records: 0  Duplicates: 0  Warnings: 0

例2:

# 带参数的添加字段
MariaDB [db_4]> alter table newdatas add email varchar(255) not null default '';
Query OK, 0 rows affected (0.012 sec)
Records: 0  Duplicates: 0  Warnings: 0

例3:

# 指定字段的插入位置
MariaDB [db_4]> alter table newdatas add sex varchar(40) not null default '0' after name;
Query OK, 0 rows affected (0.009 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql修改字段名

命令:

alter table [表名] change [原字段名] [新字段名] [字段类型] [字段属性] [位置]

例:

# 注意修改字段名时,需要添加字段的类型
MariaDB [db_4]> alter table newdatas change sex sexx varchar(50);
Query OK, 0 rows affected (0.018 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql修改字段类型

命令:

alter table [表名] modify [字段名] [字段类型] [字段属性] [位置]

例:

MariaDB [db_4]> alter table newdatas modify sex varchar(10) not null default '0';
Query OK, 0 rows affected (0.017 sec)              
Records: 0  Duplicates: 0  Warnings: 0
MariaDB [db_4]> desc newdatas;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| name  | varchar(50)  | YES  |     | NULL    |       |
| sex   | varchar(10)  | NO   |     | 0       |       |
| age   | varchar(50)  | YES  |     | NULL    |       |
| email | varchar(255) | NO   |     |         |       |
+-------+--------------+------+-----+---------+-------+
4 rows in set (0.005 sec)

mysql删除字段的命令

命令:

# 删除字段
alter table [表名] drop [字段名]
# 数据不可逆,会删除字段下的所有数据

例:

MariaDB [db_4]> alter table newdatas drop sex;
Query OK, 0 rows affected (0.009 sec)
Records: 0  Duplicates: 0  Warnings: 0
MariaDB [db_4]> desc newdatas;
+-------+--------------+------+-----+---------+-------+
| Field | Type         | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| name  | varchar(50)  | YES  |     | NULL    |       |
| age   | varchar(50)  | YES  |     | NULL    |       |
| email | varchar(255) | NO   |     |         |       |
+-------+--------------+------+-----+---------+-------+
3 rows in set (0.003 sec)
alter table newdatas drop sex;

以上就mysql中添加新字段,修改字段名以及删除字段的方法,大家可以参考一下。

标签:
声明:无特别说明,转载请标明本文来源!