SQL UPDATE语句

时间:2019-04-17 07:50:35

标签: sql postgresql join sql-update

我有这个查询,返回了我的ID

select id, default_code from product_product ou
where (select count(*) from product_product inr
where inr.default_code = ou.default_code) > 1 and ou.active = false

但是此语句出现语法错误

update product_product ou
where (select count(*) from product_product inr
where inr.default_code = ou.default_code) > 1 and ou.active = false set uo.default_code = uo.default_code || 'A';

ERROR:  syntax error at or near "where"
LINE 2:     where (select count(*) from product_product inr

如何正确更新从第一条语句中检索到的ID

2 个答案:

答案 0 :(得分:2)

您可以尝试以下操作-使用JOIN

update product_product ou
set default_code = concat(ou.default_code, 'A')
from 
 (
   select inr.default_code,count(*) from product_product inr
    group by inr.default_code having count(*)>1
 )A
where A.default_code = ou.default_code and ou.active = false

答案 1 :(得分:2)

正确:

update
    product_product ou
set
    default_code = ou.default_code || 'A'
from
    (
        select default_code
        from product_product
        group by default_code
        having count(*) > 1
    ) inr
where
    not ou.active
    and ou.default_code = inr.default_code