【发布时间】:2021-02-13 06:48:49
【问题描述】:
场景:
一家工厂每天生产各种尺寸和规格 (swg) 的钢管,记录并存储在 pipe_production 表中(管道表的 pipe_id 外键)。该工厂还有定期向其销售管道的客户,根据要求创建发票并将其记录在发票表中。随后,与每个发票相关的管道存储在 pipe_invoices 表中。当销售团队的成员对发票进行授权时,invoices 表中的授权列从 false 切换为 true (0 => 1 in),并表示这些管道将被出售并应从库存中移除。
我正在寻找一个查询来生成库存表,以便在现场准确评估管道。但是,我只想找出生产的管道和授权发票管道之间的区别。
应用程序正在 Laravel 框架上构建。
表格:管道
id | description | swg | min_weight | max_weight
1 | 2" X 2" | 16 | 10 | 11
2 | 2" X 2" | 18 | 8 | 19
3 | 1" X 2" | 18 | 4 | 6
表:pipe_productions
id | pipe_id | quantity | production_date
1 | 1 | 1000 | 2020-10-1
2 | 2 | 2000 | 2020-10-1
3 | 3 | 5500 | 2020-10-1
表格:发票
id | client_id | authorised | loaded | invoice_date
1 | 1 | 0 | 0 | 2020-10-09
2 | 2 | 1 | 0 | 2020-10-09
3 | 2 | 1 | 1 | 2020-10-09
表:pipe_invoices
id | invoice_id | pipe_id | quantity
1 | 1 | 3 | 2000
2 | 1 | 1 | 1000
3 | 2 | 2 | 1000
编辑: 我的当前查询仅获取 pipe_production 和 pipe_invoices 之间的区别。它不考虑发票未经授权且不应删除的情况。
SELECT *, coalesce(a.quantity, 0)-coalesce(b.quantity, 0) as diff
FROM
(SELECT pipe_id, sum(quantity) as quantity
FROM pipe_productions
GROUP BY pipe_id) a
LEFT JOIN
(SELECT pipe_id, sum(quantity) as quantity
FROM pipe_invoices
GROUP BY pipe_id) b
on a.pipe_id = b.pipe_id
LEFT JOIN pipes
on a.pipe_id = pipes.id
WHERE coalesce(a.quantity, 0)-coalesce(b.quantity, 0) != 0
ORDER BY swg asc, pipe_description desc
【问题讨论】:
标签: mysql sql laravel join difference