我有三张桌子:
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 |
+-------+--------+
所以我需要做的是计算TableB中的总金额,其中id_a =(1或我发布的id)AND id_c的状态是1或0,并将其设置为总列中的TableA,我在TableA中的字段total
上方发布的表格中的数据,其中id_a = 1将包含6
值。
我试图通过这种方式进入我的查询:
UPDATE TableA SET total=(SELECT SUM(amount) as sum FROM TableB WHERE id_a = 1 GROUP BY(sum))
但这是错误的(我认为)。怎么会对此有好的疑问?
答案 0 :(得分:1)
您可以在内部INNER JOIN
中的TableB和TableC之间使用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
答案 1 :(得分:1)
试试这个
UPDATE TableA SET total=(SELECT SUM(amount) FROM TableB WHERE id_a = 1)