update命令
1.update 语句更新数据操作
更新表数据,将id=10001改成id=100
mysql> update teacher2 set id =100 where id = 10001;
Query OK, 1 row affected (0.08 sec)
Rows matched: 1 Changed: 1 Warnings: 0
2.批量更改id字段,使id字段当前值全部+1;
mysql> update teacher2 set id = id+1 order by id desc;
Query OK, 5 rows affected (0.39 sec)
Rows matched: 5 Changed: 5 Warnings: 0
在进行字段修改的时候有可能会遇到主键冲突的情况.如果遇到主键冲突的话请按照规则添加排序.
id字段增大的话,将排序规则更改为 order by id desc;
id字段减小的话,将排序规则更改为 order by id ;
mysql> update teacher2 set id= id+1;
ERROR 1062 (23000): Duplicate entry '2' for key 'PRIMARY'
3.如果要修改的内容中要限制修改多少行数据的话,使用limit命令,
update tea1 set dept_id = 666 limit 2;
Query OK, 2 rows affected (0.01 sec)
Rows matched: 2 Changed: 2 Warnings: 0
随机修改两条最先查到的记录值,将dept_id修改成 666;
4.如果指定修改id为最大两条或者最小两条的dept_id记录值 使用order by 进行配合使用.
update tea1 set dept_id = 100 order by id limit 2;
Query OK, 2 rows affected (0.38 sec)
Rows matched: 2 Changed: 2 Warnings:
表示将id最小的两条的dept_id的值修改成100;
5.修改制定数据,或者指定范围的数据的某几条数据.
update tea1 set dept_id = 99 where id > 2 order by id limit 2;
Query OK, 2 rows affected (0.07 sec)
Rows matched: 2 Changed: 2 Warnings: 0
表示将id > 2 的数据条目的最小的两条的dept_id的值修改成99
6.同时修改多个表的数据.或者进行数据表中数据参考修改.不能在命令中只指定一张表.
update tea1,teacher2 set tea1.name = teacher2.name ,tea1.dept_id= teacher2.dept_id where tea1.id = teacher2.id;
Query OK, 5 rows affected (0.08 sec)
Rows matched: 5 Changed: 5 Warnings: 0
连表修改.将tea1的所有id等于teacher2id号的name字段修改成与teacher2的数据字段相同.
只要在命令中体现的表名称都要在update tab_1,tab_2上体现出来.
7.如果在关闭自动提交配置的话 在修改数据错误以后可以进行rollback进行事务的回滚.
关闭自动提交事务.
set autocommit = 0;
提交事务
commit;
回滚
rollback;
8.课后题
将所有学号小于等于100的学生系更改成education;
9.课后题
将姓名为ruth且id在100和200之间的老师的姓名改成carey;
update tea1 set name = "Creay" where name = "Liu liu" and 3<id<5;
Query OK, 1 row affected (1.71 sec)
Rows matched: 1 Changed: 1 Warnings: 0
浙公网安备 33010602011771号