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

发布于:2023-09-14 ⋅ 阅读:(196) ⋅ 点赞:(0)

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。


网站公告

今日签到

点亮在社区的每一天
去签到