我希望更新的实际字段根据条件进行更改。我遇到的现有示例仅允许更改更新的值,而不是字段。这就是我的尝试:
UPDATE conversations
CASE WHEN conv_author_id = $uid THEN SET conv_viewed_author = $d
ELSE SET conv_viewed_recipient = $d END
WHERE conv_id = $id
然而,这给我一个语法错误。
如何将实际字段更新为有条件的?
答案 0 :(得分:2)
您可以随时执行以下操作:
UPDATE conversations
SET
conv_viewed_author = (
CASE conv_author_id
WHEN $uid THEN $d
ELSE conv_viewed_author
END
),
conv_viewed_recipient = (
CASE conv_author_id
WHEN $uid THEN conv_viewed_recipient
ELSE $d
END
)
WHERE conv_id = $id
答案 1 :(得分:2)
这应该可以解决问题:
UPDATE conversations
SET
conv_viewed_author = IF(conv_author_id = $uid, $d, conv_viewed_author),
conv_viewed_recipient = IF(conv_author_id = $uid, conv_viewed_recipient, $d)
WHERE
conv_id = $id;