21

我有一个给定结构的表,现在我想编写一个查询,将 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

4 回答 4

34

如果您不关心哪一行被更新,我会非常谨慎地这样做(请为此在表中添加一个 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 条记录,我们将返回一个 CTID,该 CTID 对应于符合 WHERE 子句的行。

于 2012-07-11T12:10:20.150 回答
6

我找到了一个方法

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)
于 2012-07-11T12:33:15.017 回答
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 ;

问候

于 2013-11-13T17:48:11.170 回答
0

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

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

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

ALTER TABLE product_child SET WITH OIDS;

于 2020-09-02T11:51:03.917 回答