我希望运行以下查询:
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'
是否可以将其合并为一个查询?
答案 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')