如何更新连接值总和的字段?

时间:2014-08-02 14:29:11

标签: mysql sql sql-update

我有三张桌子。表市场包含所有项目及其价格。表用户包含所有用户及其余额的列表。表已购买包含已售商品的ID和买家的ID。我需要减去用户在商品上花费的价格。当我进行此查询时

`UPDATE market m
JOIN bought b ON m.id=b.id AND m.status="need"
JOIN users u ON u.id=b.buyer
SET m.status="sold", m.date=CURRENT_TIMESTAMP, u.balance = u.balance - m.price`

仅在一线市场价值上更新余额。我如何减去所有价格?

// ===========

用户

身份余额

1 100

// ===========

市场

ID价格

1 1

2 2

3 3

// ===========

id买家

1 1

3 1

1 个答案:

答案 0 :(得分:0)

这是您的查询:

UPDATE market m JOIN
       bought b
       ON m.id = b.id AND m.status = 'need' JOIN
       users u
       ON u.id=b.buyer
    SET m.status = 'returned',
        m.date = CURRENT_TIMESTAMP,
        u.balance = u.balance - m.price;

当多行匹配时,则任意选择一行进行更新。更新不会累积。你可以得到你想要的,但你需要两个更新,一个有聚合:

UPDATE users u JOIN
       (select b.buyer, sum(price) as sumprice
        from market m JOIN
             bought b
             ON m.id = b.id AND m.status = 'need'
       ) mb
       ON u.id = b.buyer
    SET u.balance = u.balance - m.price;

UPDATE market m JOIN
       bought b
       ON m.id = b.id AND m.status = 'need'
    SET m.status = 'returned',
        m.date = CURRENT_TIMESTAMP;