我正在学习使用MySQL,因此我尝试进行简单的库存管理。 如果我删除发票,我怎么能不只是从发票表和invoiceItemTable中删除,而是更新"金额"在我的库存表中右侧存储的减法值列?因为如果我想做
SUM(inventory.amount) - SUM(SELECT amount FROM InvoiceItemTable WHERE invoice_id = 1
GROUP BY Product_id)
这将失败,因为子查询有超过1行。下面你可以看到我的数据库结构。
InvoceTable
+---+----------------+----------+
|ID | invoice_number | Store_id |
+---+----------------+----------+
| 1 | 1234 | 1 |
+---+----------------+----------+
InvoiceItemTable
+---+----------------+------------+---------+
|ID | invoice_id | Product_id | Amount |
+---+----------------+------------+---------+
| 1 | 1 | 1 | 5 |
+---+----------------+------------+---------+
| 2 | 1 | 1 | 5 |
+---+----------------+------------+---------+
| 3 | 2 | 1 | 10 |
+---+----------------+------------+---------+
Inventory
+---+----------------+---------+----------+
|ID | Product_id | Amount | Store_id |
+---+----------------+---------+----------+
| 1 | 1 | 15 | 1 |
+---+----------------+---------+----------+
| 2 | 2 | 15 | 1 |
+---+----------------+---------+----------+
| 3 | 2 | 15 | 2 |
+---+----------------+---------+----------+
更新 查询后的期望:
InvoceTable
+---+----------------+----------+
|ID | invoice_number | Store_id |
+---+----------------+----------+
| | | |
+---+----------------+----------+
InvoiceItemTable
+---+----------------+------------+---------+
|ID | invoice_id | Product_id | Amount |
+---+----------------+------------+---------+
| 3 | 2 | 1 | 10 |
+---+----------------+------------+---------+
Inventory
+---+----------------+---------+----------+
|ID | Product_id | Amount | Store_id |
+---+----------------+---------+----------+
| 1 | 1 | 5 | 1 |
+---+----------------+---------+----------+
| 2 | 2 | 5 | 1 |
+---+----------------+---------+----------+
| 3 | 2 | 15 | 2 |
+---+----------------+---------+----------+
答案 0 :(得分:1)
你需要在子查询中使用sum:
select SUM(inventory.amount) - (SELECT SUM(amount) FROM InvoiceItemTable WHERE invoice_id = 1 GROUP BY Product_id)
from inventory
检查sqlfiddle您的数据库方案和正在运行的查询。
此查询应根据invoiceitemtable表减少Inventory表的amount列:
update Inventory set Amount = Amount - (SELECT SUM(amount) FROM InvoiceItemTable WHERE invoice_id = 1 AND Product_id = Inventory.Product_id GROUP BY Product_id)
答案 1 :(得分:-1)
SUM(inventory.amount) - (SELECT SUM(amount) FROM InvoiceItemTable WHERE invoice_id = 1 GROUP BY Product_id)