使用两个表中的数学运算更新字段

时间:2014-11-12 16:32:40

标签: mysql sql-update sum

我有两个包含两个数字字段的表。

mysql> desc cc_call;
+-----------------------+---------------+------+-----+---------------------+----------------+
| Field                 | Type          | Null | Key | Default             | Extra          |
+-----------------------+---------------+------+-----+---------------------+----------------+
| card_id               | bigint(20)    | NO   |     | NULL                |                | 
| sessionbill           | float         | YES  |     | NULL                |                | 

mysql> desc cc_card;
+---------------------+---------------+------+-----+---------------------+----------------+
| Field               | Type          | Null | Key | Default             | Extra          |
+---------------------+---------------+------+-----+---------------------+----------------+
| id                  | bigint(20)    | NO   | PRI | NULL                | auto_increment | 
| credit              | decimal(15,5) | NO   |     | 0.00000             |                | 

我需要用两个字段的总和更新cc_card.credit字段。

我首先尝试使用SELECT进行数学运算:

SELECT cc_call.sessionbill+cc_card.credit 
FROM cc_card WHERE cc_card.id = (SELECT cc_call.card_id 
FROM cc_call 
WHERE cc_call.card_id=cc_call.id);

出现以下输出错误:

  

ERROR 1054(42S22):'字段中的'cc_call.sessionbill'列未知   列表“

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

你应该使用JOIN:

UPDATE cc_card
JOIN cc_call ON cc_call.card_id = cc_card.id
SET cc_card.credit = cc_call.sessionbill+cc_card.credit