gpt4 book ai didi

MySQL 与库存维护

转载 作者:行者123 更新时间:2023-11-29 15:36:56 25 4
gpt4 key购买 nike

我有一个简单的程序来管理某些车辆的燃油发放状态

即包括下表

商店商品

+---------+-----------+--------+
| item_id | item_name | status |
+---------+-----------+--------+
| 1 | Diesel | 1 |
+---------+-----------+--------+

tbl_车辆

+------------+------------+
| vehicle_id | vehicle_no |
+------------+------------+
| 1 | 4545 |
| 2 | 4546 |
| 3 | 4547 |
| 18 | 4548 |
+------------+------------+

store_update_stock

+-----------------+------------+---------+--------+
| update_stock_id | bill_date | bill_no | status |
+-----------------+------------+---------+--------+
| 1 | 2019-09-25 | 123 | 1 |
| 2 | 2019-09-26 | 456 | 1 |
+-----------------+------------+---------+--------+

store_update_stock_details

+-------------------------+-----------------+------+-----+--------+
| update_stock_details_id | update_stock_id | item | qty | status |
+-------------------------+-----------------+------+-----+--------+
| 1 | 1 | 1 | 900 | 1 |
| 2 | 2 | 1 | 800 | 1 |
+-------------------------+-----------------+------+-----+--------+

tbl_fuel

+---------+------------+-------------+------+----------+
| fuel_id | vehicle_id | issued_date | item | fuel_qty |
+---------+------------+-------------+------+----------+
| 1 | 2 | 2019-09-25 | 1 | 50 |
| 2 | 2 | 2019-09-25 | 1 | 50 |
| 3 | 18 | 2019-09-26 | 1 | 25 |
| 4 | 2 | 2019-09-27 | 1 | 50 |
+---------+------------+-------------+------+----------+

我使用了以下代码

select sum(store_update_stock_details.qty) - tbl_fuel.fuel_qty  as qty
from store_update_stock_details
inner join store_update_stock on store_update_stock_details.update_stock_id=store_update_stock.update_stock_id
join store_item on store_update_stock_details.item=store_item.item_id
join tbl_fuel on store_item.item_id=tbl_fuel.item
where store_update_stock.status=1
group by store_item.item_id

期望出局

+------+
| qty |
+------+
| 1525 |
+------+

但是代码生成以下输出

+------+
| qty |
+------+
| 6750 |
+------+

我不明白可能出了什么问题。谁能帮我吗?

最佳答案

查询的主要问题是,由于 tbl_fuel 中有多个行与库存更新详细信息表中的相同 item 匹配,因此最终会得到多个正在求和的结果集中的行(因此结果大于预期结果)。要解决此问题,您需要分别对每个表中的项目进行求和,然后减去结果:

select susd.qty - tf.fuel_qty  as qty
from (select susd.item, sum(susd.qty) AS qty
from store_update_stock_details susd
join store_update_stock sus on sus.update_stock_id = susd.update_stock_id
where sus.status = 1
group by item) susd
join store_item si on susd.item = si.item_id
join (select item, sum(fuel_qty) AS fuel_qty
from tbl_fuel
group by item) tf on si.item_id=tf.item

输出:

qty
1525

Demo on dbfiddle

关于MySQL 与库存维护,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58143472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com