更新查询MySQL PDO时的情况

时间:2019-04-14 06:50:32

标签: php mysql pdo

如何使用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();

1 个答案:

答案 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列的分配。