mysql语法之update

Update 语句:

1、作用:Update 语句用于修改表中的数据。
语法:UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值

1.建表语句:
create table table1(
idd varchar(10),
val varchar(20)
);
create table table2(
idd varchar(10),
val varchar(20)
);

2.插入数据:

insert into table1 values (‘01’,‘1111’);
insert into table1 values (‘02’,‘222’);
insert into table1 values (‘02’,‘2222’);
insert into table1 values (‘03’,‘3333’);
insert into table1 values (‘04’,‘4444’);
insert into table1 values (‘06’,‘6666’);

insert into table2 values (‘01’,‘aaaa’);
insert into table2 values (‘02’,‘bbbb’);
insert into table2 values (‘03’,‘cccc’);
insert into table2 values (‘04’,‘dddd’);
insert into table2 values (‘05’,‘eee’);

(1)列一:更新某一行中的一个列

**update table1 set val='022222' where id='02'**

(2)更新某一行中的若干列
alter table table1 add column cs varchar(45) ;
alter table table2 add column cs varchar(45) ;

update table1 set val=‘022222’,cs=‘222’ where idd='02’

(3) mysql数据库update更新表中某个字段的值为另一张表的某个字段值

update table1 a left join table2 b on a.idd= b.idd set a.val = b.val where a.idd=b.idd;
在这里插入图片描述
(4)mysql查询出一张表的数据值去更新另一张表的数据值

update table1 set val=(SELECT val FROM table2 where idd=‘01’) where idd=‘03’

(5)对某些字段变量+1,常见的如:点击率、下载次数等这种直接将字段+1然后赋值给自身
update table1 set val=val+1 where idd=‘06’

(6)将同一个表中的一些记录更新到另外一些记录中
create table price
(
id int,
month int,
r_id int,
price int
);

insert into price(id,month,r_id,price) values(1,1,1,2);
insert into price(id,month,r_id,price) values(2,1,1,4);
insert into price(id,month,r_id,price) values(3,2,1,5);
insert into price(id,month,r_id,price) values(4,2,2,5);

表:price
ID month R_ID Price
1 1 1 2
2 1 2 4
3 2 1 5
4 2 2 5

要求:如何将表中2月份的产品price更新到1月份中
处理方法:要找到2月份中和1月份中ID相同的E_ID并更新price到1月份中

方法一:update price as a,price as b set a.price=b.price where a.r_ID=b.r_ID and a.month=1 and b.month=2

方法二:update price as a,(select * from price where month=2) as b set a.price=b.price where a.r_ID=b.r_ID and a.month=1

(7)mysql 下sql语句 update 字段=字段+字符串 表字段某一个原值加一个字符串

create table a
(
id VARCHAR(40),
phone VARCHAR(40),
email VARCHAR(40)
)

insert into a VALUES (1,18078526042,’’);
insert into a VALUES (2,18078526043,’’);
insert into a VALUES (3,18078526044,’’);
在这里插入图片描述
1、要求将所有email为空的字段值改成phone连接字符串@qq.com的格式

#这是单独执行一条数据
SELECT * FROM a where id=1;
update a set email=concat(phone,’@qq.com’) where id=‘1’;
在这里插入图片描述
#批量执行多条数据
SELECT * FROM a where email=’’;
update a set email=concat(phone,’@qq.com’) where email=’’;
在这里插入图片描述

提醒:mysql下sql语句令某字段值等于原值加上一个字符串
update 表明 SET 字段= ‘feifei’ || 字段; (postgreSQL 用 || 来连贯字符串)
MySQL连贯字符串不能利用加号(+),而利用concat。

发布了91 篇原创文章 · 获赞 2 · 访问量 7057

猜你喜欢

转载自blog.csdn.net/qq_43211632/article/details/104639541