表结构
1,添加字段
添加新字段
alter table 表名 add 字段 类型;
mysql> alter table t3 add math int(10);
\\添加字段
mysql> alter table t3 add (chinese int(10),english int(10));
\\添加多个字段,中间用逗号隔开
添加到指定字段下
alter table 表名 add 添加的字段(和类型) after name;
\\把添加的字段放到name后面
mysql> alter table t9 add id char(10) after home;
Query OK, 0 rows affected (0.04 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc t9;
+----------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+---------------+------+-----+---------+-------+
| name | char(10) | YES | | NULL | |
| hostname | char(10) | NO | | NULL | |
| ip | char(20) | YES | | NULL | |
| math | int(3) | YES | | NULL | |
| chinese | int(10) | YES | | NULL | |
| english | int(10) | YES | | NULL | |
| home | char(10) | YES | | NULL | |
| id | char(10) | YES | | NULL | |
| sex | enum('w','m') | YES | | NULL | |
+----------+---------------+------+-----+---------+-------+
9 rows in set (0.00 sec)
添加的字段放第一个
alter table 表名 add 添加的字段(和类型) first;
\\把添加的字段放在第一个
mysql> alter table t9 add name char(10) first;
Query OK, 0 rows affected (0.04 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc t9;
+----------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+---------------+------+-----+---------+-------+
| name | char(10) | YES | | NULL | |
| hostname | char(10) | NO | | NULL | |
| ip | char(20) | YES | | NULL | |
| math | int(3) | YES | | NULL | |
2,修改字段和类型
修改名称、数据类型、类型
alter table 表名 change 旧字段 新字段 类型;
\\change 修改字段名称,类型,约束,顺序
mysql> alter table t3 change max maxs int(15) after id;
\\修改字段名称与修饰并更换了位置
修改字段类型、约束、顺序
alter table 表名 modify 字段 类型;
\\modify 不能修改字段名称
mysql> alter table t3 modify maxs int(20) after math;
\\修改类型并更换位置
删除字段
alter table 表名 drop 字段名;
\\drop 丢弃的字段。
mysql> alter table t3 drop maxs;
\\删除maxs 字段
3,插入数据(添加记录)
mysql> create table t3(id int, name varchar(20), sex enum('m','f'), age int);
\\字符串必须引号引起来
\\记录与表头相对应,表头与字段用逗号隔开。
添加一条记录
insert into 表名(字段1,字段2,字段3,字段4) values(1,"tom","m",90);
mysql> insert into t3(id,name,sex,age) values(1,"tom","m",18);
Query OK, 1 row affected (0.00 sec)
注:添加的记录与表头要对应,
添加多条记录
mysql> insert into t3(id,name,sex,age) values(2,"jack","m",19),(3,"xiaoli","f",20);
Query OK, 2 rows affected (0.34 sec)
使用 set 添加记录
mysql> insert into t3 set id=4,name="zhangsan",sex="m",age=21;
Query OK, 1 row affected (0.00 sec)
更新修改记录
update 表名 set 修改的字段 where 给谁修改;
mysql> update t3 set id=6 where name="xiaoli";