pgsql和oracle的批量更新,更新多条数据成不同的值

pgsql一次更新多个字段

必须使用(select ‘22’,12)或者 (‘22’,12)

#update product set (name)=('22') where id=25	报错
update product set (name,price)=('22',12) where id=25
update product set (name,price)=( select  '22',12) where id=25

oracle一次更新多个字段

必须使用(select ‘22’,12 from dual)

#update product set (name,price)=('22',12) where id=25  	报错!!
update product set (name,price)=(select '22',12 from dual) where id=25

批量更新需求:

product表里,id=21的数据设置name=商品21,price=210,id=22的数据设置name=商品22,price=220,等等。即需要更新多条数据,且不同数据修改后的值不一样。
下面的pgsql的sql where exists可替换成 where product.id in (21,22)。
oracle的写法类似,加上from dual就行,后面不再赘述。

update product 
    set (name,price)=  
        (select name,price from 
            (select 21 id, '商品21' name,210 price union 
            select 22 id, '商品22' name,220 price ) t1 where product.id=t1.id
         )
    where exists (
        select 1 from 
            (select 21 id union select 22 id) t2  where product.id=t2.id 
    
    )

注意两个where条件都需要。如果没有第二个where,表内所有的数据都会更新,但set里没有id=25的数据,所以会更新成null。
在mybatis里可以i传list做参数,用foreach拼接临时表t1。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值