简体   繁体   English

如何从第一个表到其他两个表更新记录?

[英]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. 因此,我需要做的是从TableB中计算ID_a =(1或我发布的ID)且id_c的状态为1或0的总金额,并将其设置为TableA中的total列,以获取我在id_a = 1的TableA中的字段total上方发布的表将包含6值。

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 . 您可以在内部SELECT在TableB和TableC之间使用INNER JOIN

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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