如何通过一个查询更新多行?

时间:2016-06-03 14:45:00

标签: mysql sql sql-update

我有这张桌子:

// user
+----+----------+---------------------+-------------+
| id |   name   |       email         |  reputation |
+----+----------+---------------------+-------------+
| 1  | Jack     | jack12@google.com   | 10          |
| 2  | John     | J_1343@ymail.com    | 1423        |
| 3  | Ali      | 1992Ali@yahoo.com   | 322         |
| 4  | Peter    | p.54@gmail.com      | 950         |
+----+----------+---------------------+-------------+

我也有两个身份证号码。 $op$user。我希望通过2(适用于$op)和15(适用于$user)加上当前的声誉。所以这是预期的输出:

$op = 3;
$user = 1;

// user
+----+----------+---------------------+-------------+
| id |   name   |       email         |  reputation |
+----+----------+---------------------+-------------+
| 1  | Jack     | jack12@google.com   | 25          |
| 2  | John     | J_1343@ymail.com    | 1423        |
| 3  | Ali      | 1992Ali@yahoo.com   | 324         |
| 4  | Peter    | p.54@gmail.com      | 950         |
+----+----------+---------------------+-------------+

我如何通过一个查询来做到这一点?

我可以通过两个独立的查询来做到这一点:

UPDATE user SET reputation = reputation + 2 WHERE id = :op
UPDATE user SET reputation = reputation + 15 WHERE id = :user

2 个答案:

答案 0 :(得分:3)

为什么不尝试:

UPDATE user SET reputation = reputation + (CASE id WHEN :op THEN 2 WHEN :user THEN 15 ELSE 0 END) WHERE user in (:user, :op)

答案 1 :(得分:0)

试试这个

UPDATE user SET reputation = (CASE WHEN id = :op THEN reputation + 2 
                                  WHEN id = :user THEN reputation + 15
                                  END)