-1

我有三张桌子:

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) 并且 id_c 的状态为 1 或 0 并将其设置到 TableA in total 列中,用于数据我total在 TableA 中的字段上方发布的表,其中 id_a = 1 将包含一个6值。

我正在尝试通过这种方式进行查询:

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

但这是错误的(我认为)。对此有何好查询?

4

2 回答 2

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
于 2013-01-18T01:05:08.403 回答
1

试试这个

   UPDATE TableA SET total=(SELECT SUM(amount)  FROM TableB WHERE id_a = 1)
于 2013-01-18T01:06:40.863 回答