仅当行存在时更新(如果然后)

时间:2019-02-12 01:42:14

标签: postgresql sql-update

我希望运行以下查询:

UPDATE
    creator.contacts
SET
    status = 'accepted'
WHERE
    (
        account_id = $1
        AND
        contact_id = $2
    )
    OR
    (
        account_id = $2
        AND
        contact_id = $1
    )

但仅在特定条件下,我使用以下条件进行查询:

SELECT
    COUNT(*)
FROM
    creator.contacts
WHERE
    account_id = $1
    AND
    status = 'pending'

是否可以将其合并为一个查询?

1 个答案:

答案 0 :(得分:1)

您可以将该条件作为WHERE测试添加到您的EXISTS子句中。请注意,您需要在现有()子句周围添加WHERE,以确保正确评估逻辑运算符的顺序:

UPDATE
    creator.contacts
SET
    status = 'accepted'
WHERE
    ((
        account_id = $1
        AND
        contact_id = $2
    )
    OR
    (
        account_id = $2
        AND
        contact_id = $1
    ))
    AND
        EXISTS (SELECT * 
                FROM  creator.contacts
                WHERE
                   account_id = $1
                AND
                   status = 'pending')