如何使用CASE WHEN
在MySQL和PDO中运行更新查询。
以下查询将CASE
列更新为0。
$query= "Update payments SET
total = :total,
paid = CASE
WHEN paid > :new THEN paid = :new
ELSE paid
END,
due = CASE
WHEN paid < :new THEN due = :new - paid
ELSE due
END
WHERE id = :id ";
$update= $db->prepare($query);
$update->bindparam(':total',$new);
$update->bindparam(':new',$new);
$update->bindparam(':id',$id);
$update->execute();
答案 0 :(得分:2)
请勿尝试将值分配给CASE WHEN语句内的列,因为您已经在执行此操作。
CASE WHEN将评估为满足条件的值。
试试这个代码
UPDATE payments SET
total = :total,
paid = (CASE WHEN paid > :new THEN :new ELSE paid END),
due = (CASE WHEN paid < :new THEN (:new - paid) ELSE due END)
WHERE id = :id
我删除了case语句中对pay和due列的分配。