简体   繁体   中英

How to update one table based on another one?

I have these two tables:

// 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 |
+----+------------+---------+------+

I'm trying to sum the number of reputation column from rep table where done is Null for specific user and then add it to total_rep column from user table. So it is expected output:

// specific user
$id = 2;

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

Note: Then I will update done column and set all Null values for that user to 1 . (this is not my question, I can do that myself)

How can I do that?

One way to do it is to use the result of a subquery as a scalar value in an update statement.

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;

You can't update two tables in one statement, so you will need to execute a transaction. Or maybe in some code do the next thing I'll make it in 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
}

You have to take the data and update firstable the reputation table to clean it and then the user table to sum the rep values

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM