我有两张桌子:
用户
| id | amount |
---------------
| 1 | 10 |
| 2 | 20.50 |
| 3 | 0 |
| 4 | 80 |
| 5 | 0 |
---------------
vehicle_travel
| id | user_id | costprice | status |
--------------------------------------
| 1 | 1 | 80.00 | active |
| 2 | 1 | 20.00 | expired |
| 3 | 2 | 130.50 | active |
| 4 | 5 | 325.00 | active |
| 5 | 3 | 99.50 | expired |
--------------------------------------
我想UPDATE
用户表和SET
users.amount 到 users.amount + vehicle_travel.costprice WHERE
users.id 等于 vehicle_travel.user_id AND
vehicle_travel.status 等于'过期'
这是我的完整查询:
UPDATE users
SET users.amount=users.amount+vehicle_travel.costprice
WHERE users.id=vehicle_travel.user_id
AND vehicle_travel.status='expired'
但我不断从phpMyAdmin获得未知列错误。
我做错了什么?
答案 0 :(得分:1)
试试这个;)
UPDATE users
INNER JOIN vehicle_travel
ON users.id = vehicle_travel.user_id
AND vehicle_travel.status = 'expired'
SET users.amount = users.amount + vehicle_travel.costprice
<强> 编辑: 强>
UPDATE users
INNER JOIN (
SELECT SUM(costprice) AS costprice, user_id
FROM vehicle_travel
WHERE status = 'expired'
GROUP BY user_id
) vehicle_travel
ON users.id = vehicle_travel.user_id
SET users.amount = users.amount + vehicle_travel.costprice
答案 1 :(得分:1)
您需要使用JOIN
。如果您没有指定表名,那么对于那些引用未指定表的列,您将遇到未知列错误。
UPDATE users
INNER JOIN vehicle_travel ON vehicle_travel.user_id = users.id
SET users.amount=users.amount+vehicle_travel.costprice
WHERE vehicle_travel.status='expired'