如何根据另一个表更新一个表?

时间:2016-06-01 21:51:15

标签: php mysql sql sql-update

我有这两个表:

// user
+----+-------+------------+
| id |  name | total_rep  |
+----+-------+------------+
| 1  | Jack  | 100        |
| 2  | Peter | 334        |
| 3  | John  | 1          |
| 4  | Ali   | 5463       |
+----+-------+------------+

// rep
+----+------------+---------+------+
| id | reputation | id_user | done |
+----+------------+---------+------+
| 1  | 5          | 2       | 1    |
| 2  | 2          | 3       | 1    |
| 3  | 15         | 2       | Null |
| 4  | 10         | 2       | Null |
| 5  | 5          | 4       | 1    |
| 6  | 10         | 3       | Null |
+----+------------+---------+------+

我正在尝试将reputation表中rep列的数量加到特定用户的doneNull,然后将其添加到total_rep来自user表的列。所以它是预期的输出:

// specific user
$id = 2;

// user
+----+-------+------------+
| id |  name | total_rep  |
+----+-------+------------+
| 1  | Jack  | 100        |
| 2  | Peter | 359        | -- this is updated
| 3  | John  | 1          |
| 4  | Ali   | 5463       |
+----+-------+------------+

注意:然后我会更新done列并将该用户的所有Null值设置为1(这不是我的问题,我可以自己做)

我该怎么做?

2 个答案:

答案 0 :(得分:1)

一种方法是在更新语句中将子查询的结果用作scalar value

UPDATE `user` 
SET total_rep = total_rep + (
    SELECT SUM(reputation) AS rep_sum FROM `rep` WHERE done IS NULL AND id_user = 2)
WHERE id = 2;

答案 1 :(得分:0)

您无法在一个语句中更新两个表,因此您需要执行一个事务。或者也许在某些代码中做下一件我将用PHP编写的东西

$query_result=DB::select('Select sum(reputation) as reputation, id_user from rep where done is null group by id_user');

foreach($query_result as $result){
    //update the data
}

您必须获取数据并更新第一个信誉表以清除它,然后更新用户表以汇总重复值