如何更新最终关联记录

时间:2017-01-17 14:13:42

标签: mysql

我有items的{​​{1}}列表。每个orders都有item字段。 fee_percentage表格中items的总和为total_price

我想要实现什么? 我想更新最后关联项目的orders字段。

fee

正如您所看到的,_________________________ __________________________________________ | order ID | total_price| | id | order_id | fee_percentage | fee | ------------------------- ------------------------------------------ | 334 | 425 | | 1 | 334 | 50 | 212 | # The `fee` should be 213 => | 2 | 334 | 50 | 212 | 的总和将为424.我想将剩余费用添加到最后一项items。 (因此,项目编号2的费用应为213)。

请帮忙吗?

这是我到目前为止所写的内容

fee

我尝试将其附加到之前的查询或更新订单记录中的last_item_id,但它不起作用。

UPDATE items AS i
LEFT JOIN orders AS o ON o.order_id = b.order_id
LEFT JOIN (
    SELECT order_id, SUM(fee) AS sum_fee
    FROM items 
    GROUP BY order_id
    WHERE deleted = 0
) AS b1 ON b1.order_id = b.order_id
SET b.fee = b.fee + (o.total_price - b1.sum_fee)
WHERE b.deleted = 0;

2 个答案:

答案 0 :(得分:1)

这有点棘手。我认为以下查询应该有效:

UPDATE items AS i
JOIN orders AS o ON i.order_id = o.orderID
JOIN (
   SELECT order_id, SUM(fee) AS sum_of_fees
   FROM items
   GROUP BY order_id
) AS i2 ON i2.order_id = o.orderID  
LEFT JOIN items AS i3 
   ON i3.order_id = o.orderID AND i3.id > i.id
SET i.fee = o.total_price - (sum_of_fees - i.fee)
WHERE i3.id IS NULL;

使用的派生表计算每order_id的费用总和。使用此值,我们可以计算所有项目的总和但当前项目为:

SUM(fee) - i.fee

需要额外的LEFT JOINitems表来识别具有最大id值的记录,这是实际正在更新的记录。

答案 1 :(得分:0)

   UPDATE items AS b 
    JOIN (
        SELECT MAX( i.id ) mid, o.curr_price - SUM( i.fee ) AS diff
        FROM items AS i
        INNER JOIN orders AS o ON i.order_id = o.order_id
        GROUP BY i.order_id
        ORDER BY i.order_id, i.id
    ) AS v ON b.id = v.mid
    SET b.fee = b.fee + v.diff WHERE v.diff <> 0;