限制postgreSQL更新命令

时间:2012-07-11 11:57:42

标签: sql postgresql

我有一个给定结构的表,现在我想编写一个查询,将2 xx产品从状态1转移到状态2.子代码目前与我无关。

master_code| child_code | status_code
-----------|------------|------------
    xx     |    xx1     |     1
    xx     |    xx2     |     1
    xx     |    xx3     |     1
    xx     |    xx4     |     2
    xx     |    xx5     |     2
    yy     |    yy1     |     3
    yy     |    yy2     |     2
    zz     |    zz1     |     1
    zz     |    zz2     |     1

我已经实施了基本检查,当我使用

update only product_child
set product_status=1
where product_status=2

所有三个xx都有代码2,我希望控制它,我期待只有一个xx会通过这个命令改变代码

4 个答案:

答案 0 :(得分:19)

如果你不关心哪一行得到更新,我会非常警惕(请为表格添加一个PK),然后你可以使用如下内容:

UPDATE
    product_child
SET
    product_status = 1
WHERE
    CTID IN ( SELECT CTID FROM product_child WHERE product_status = 2 and master_code = 'xx' LIMIT 1 )

CTID是一个唯一的行标识符 - 通过将子选择限制为1个记录,我们返回一个对应于满足WHERE子句的行的CTID。

答案 1 :(得分:4)

也许你应该用一个程序来做这件事:

CREATE or replace FUNCTION  update_status() returns character varying as $$
declare
match_ret record;
begin
SELECT * INTO match_ret FROM product_child WHERE product_status = 2 LIMIT 1 for update ;
UPDATE product_child SET status_code = '1' where child_code = match_ret.child_code ;

return match_ret.child_code ;
commit;
end ;
$$ LANGUAGE plpgsql;

然后用:

来调用它
select * from update_status()

编辑: 你也可以用'with'来做到这一点:

WITH subRequest as (
SELECT child_code FROM product_child WHERE status = 2 LIMIT 1 FOR UPDATE
)
UPDATE product_child as p
FROM subRequest
WHERE p.child_code = subRequest.child_code ;

此致

答案 2 :(得分:3)

我找到了一种方法

update only product_child
set product_status =1
where product_child_code in (select product_child_code
                from product_child
                where product_code = get_product_code('Baby Crib') 
                and product_status = 2 
                limit 5)

答案 3 :(得分:0)

John D.的答案是正确的。我只想补充一下,postgresql可以使用oid,这是确保唯一标识符的好方法,所以我更喜欢这种解决方案:

更新 product_child 组 product_status = 1 哪里 oid =(从product_child WHERE product_status = 2和master_code ='xx'LIMIT 1的SELECT oid);

请注意,如果您的数据库没有oid,则可以使用以下命令进行设置:

ALTER TABLE product_child带有OID的设置;