我一直在墙上敲了几个小时,试图弄清楚如何在一个查询中正确地做到这一点。这是相当多的搜索引导的成果。
UPDATE invoices inv INNER JOIN (
SELECT *
FROM (
SELECT invoice_id, SUM( invoice_items.tax1_value ) AS tax1_total, SUM( invoice_items.tax2_value ) AS tax2_total, SUM( invoice_items.extended_profit ) AS total_profit, SUM( invoice_items.extended_cost ) AS total_cost, SUM( invoice_items.extended ) AS subtotal, SUM( invoice_items.discount_value ) AS discount
FROM invoice_items
GROUP BY invoice_id
) AS totals
WHERE `invoice_id` = '1001')tot ON inv.invoice_id = tot.invoice_id
SET inv.tax1_total = tot.tax1_total,
inv.tax2_total = tot.tax2_total,
inv.total_profit = tot.total_profit,
inv.total_cost = tot.total_cost,
inv.subtotal = tot.subtotal,
inv.discount = tot.discount,
inv.total = ( tot.subtotal + tot.tax1_total + tot.tax2_total ) ,
inv.subtotal = tot.subtotal WHERE inv.invoice_id = '1001';
UPDATE invoices SET due = ( total - received ) WHERE invoice_id =1001
非常感谢任何帮助。
答案 0 :(得分:0)
您可以插入total
的表达式并将其用于更新:
UPDATE invoices inv INNER JOIN
(SELECT invoice_id, SUM( invoice_items.tax1_value ) AS tax1_total,
SUM( invoice_items.tax2_value ) AS tax2_total,
SUM( invoice_items.extended_profit ) AS total_profit,
SUM( invoice_items.extended_cost ) AS total_cost,
SUM( invoice_items.extended ) AS subtotal,
SUM( invoice_items.discount_value ) AS discount
FROM invoice_items
WHERE `invoice_id` = '1001'
GROUP BY invoice_id
) AS tot
ON inv.invoice_id = tot.invoice_id
SET inv.tax1_total = tot.tax1_total,
inv.tax2_total = tot.tax2_total,
inv.total_profit = tot.total_profit,
inv.total_cost = tot.total_cost,
inv.subtotal = tot.subtotal,
inv.discount = tot.discount,
inv.total = ( tot.subtotal + tot.tax1_total + tot.tax2_total ) ,
inv.subtotal = tot.subtotal,
inv.due = ( tot.subtotal + tot.tax1_total + tot.tax2_total ) - inv.received
WHERE inv.invoice_id = '1001';
上述查询还删除了join
中不必要的子查询。作为备注,最终where
也是不必要的,因为join
执行相同的过滤。