简体   繁体   中英

How to update a record from first table through the other two tables?

I have three tables:

TableA

+-------+--------+--------+
| id_a  | name   | total  |
+-------+--------+--------+
|    1  | Andrew |        |
|    2  | Jhon   |        |
+-------+--------+--------+

TableB

+-------+--------+--------+--------+
| id_b  | id_a   | amount | id_c   |
+-------+--------+--------+--------+
|    1  | 1      |    5   | 1      |
|    2  | 1      |    1   | 2      |
+-------+--------+--------+--------+

TableC

+-------+--------+
| id_c  | status |
+-------+--------+
|    1  | 1      |
|    2  | 0      |
+-------+--------+

So what I need to do is to count a total sum of amounts from TableB where id_a = (1 or my posted id) AND where status of id_c is 1 or 0 and set it into the TableA in total column, for the data in the tables I've posted above the field total in a TableA where id_a = 1 will contains a 6 value.

I'm trying to go in my query through this way:

UPDATE TableA SET total=(SELECT SUM(amount) as sum FROM TableB WHERE id_a = 1 GROUP BY(sum))

but this is way is wrong ( I think ). How would be nice query to this?

You can use an INNER JOIN between TableB and TableC in your inner SELECT .

UPDATE TableA SET
    total=(
        SELECT SUM(amount) FROM TableB
                           INNER JOIN TableC ON TableB.id_c = TableC.id_c
        WHERE id_a = 1 AND (status = 1 OR status = 0)
        GROUP BY id_a
    )
WHERE id_a = 1

尝试这个

   UPDATE TableA SET total=(SELECT SUM(amount)  FROM TableB WHERE id_a = 1)

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