SQL根据其他值更新每一行

我需要进行更新,但是每行的值都不同。

我有类似sql的

select c.id as client_id,c.name as c_name,st.id as st_id,st.name as st_name,c.default_store_type_id 
from client c
join store_type st on c.id = st.client_id

现在我需要为每个客户端进行更新:

UPDATE client c SET c.defaultStoreTypeId = st.id

我正在尝试,但是使用as

with cte (client_id,c_name,st_id,st_name)
    as (
        select c.id as client_id,st.name as st_name from client c
        join store_type st on c.id = st.client_id
        where c.id not in (9,12)
        order by c.id
    ) 

但是这里不知道如何准备UPDATE。

weiqchen 回答:SQL根据其他值更新每一行

您可以使用FROM子句:

UPDATE client c
    SET defaultStoreTypeId = st.id
    FROM store_type st 
    WHERE c.id = st.client_id;
,

您可以使用Postgres update ... set ... from ... where ...语法:

update client c
set defaultstoretypeid = s.id
from store_type s
where c.id = s.client_id;

注意:Postgres在set子句中不接受表前缀。

Demo on DB Fiddle

本文链接:https://www.f2er.com/3080086.html

大家都在问