sql进行批量更新或者一条sql写出批量更新的语句

有表如下

t_user:字段如下

id,name,phone

t_phone:字段如下

uid,phone

其中t_phone表的uid字段是外键并且唯一,他引用t_user的id字段,现需要将t_phone表的phone数据插入到t_user表中。

 

 

update的使用当针对于有关联的表时,update可以后接两个或多个表名

Mysql--针对于全部数据

update t_user,t_phone set t_user.phone = t_phone.PHONE where t_phone.UID = t_user.id;

 

Oracle关联更新方式

-- Update

update的使用当针对于有关联的表时,update可以在set或者在where通过子查询做连接查询--oracle--针对于某条数据

update t_userxx set t_userxx.phone = (select t_phonexx.phone from t_phonexx inner join t_userxx on t_userxx.id = t_phonexx.uuid where t_userxx.id = '1') where t_userxx.id = '1';

 

update的使用当针对于有关联的表时,子查询的表关联的已经声明需要修改的表

oracle--针对于全部数据--有缺陷--如果有空的数据,就会将空的数据也更新过去。

update t_userxx set t_userxx.phone = ( select t_phonexx.phone from t_phonexx where t_userxx.id = t_phonexx.uuid )

 

oracle--针对于全部数据--可以过滤空数据(exists判读是否存在)

update t_userxx set t_userxx.phone = (select t_phonexx.phone from t_phonexx where t_userxx.id = t_phonexx.uuid) where exists (select 1 from t_phonexx where t_userxx.id = t_phonexx.uuid);

 

-- 内联视图更新,update后接多表查询的结果集,用返回的列进行更新

UPDATE ( select t1.fmoney fmoney1,t2.fmoney fmoney2 from t1,t2 where t1.fname = t2.fname )t set fmoney1 =fmoney2;

 

-- merge更新,最简洁,效率最高,在大数据量更新时,优先使用这种方式。

merge into t1

using (select t2.fname,t2.fmoney from t2) t on (t.fname = t1.fname) when matched

then update set t1.fmoney = t.fmoney;

 

 

MySQL批量更新一条SQL实现

-- 批量更新,de.user_id 为外键

UPDATE tab_user tuser

SET tuser.pay_total

=

//类似于根据外层where条件在里面进行批量更新,借助子查询

CASE tuser.id

WHEN id THEN (select sum(de.pay_amout) from tab_user_details de where de.user_id = tuser.id group by de.user_id )

END

WHERE tuser.id IN (select de.user_id from tab_user_details de group by de.user_id);

 

-- 一条sql实现条件更新。

UPDATE categories

SET

display_order = CASE id

WHEN 1 THEN 3

WHEN 2 THEN 4

WHEN 3 THEN 5

END

, (可接多个进行更新)

title = CASE id

WHEN 1 THEN 'New Title 1'

WHEN 2 THEN 'New Title 2'

WHEN 3 THEN 'New Title 3'

END

WHERE id IN (1,2,3);

(这句sql 的意思是,更新display_order 字段,如果id=1 则display_order 的值为3,如果id=2 则dingdan 的值为4……

where部分不影响代码的执行,但是会提高sql执行的效率。确保sql语句仅执行需要修改的行数,这里只有3条数据进行更新,而where子句确保只有3行数据执行)

 

MySql四种常用更新手段

1、.replace into 批量更新

2、insert into ...on duplicate key update批量更新

3、创建临时表,先更新临时表,然后从临时表中update

4、使用mysql 自带的语句构建批量更新 case...when

 

  • 10
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

、小H

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值