2个表列之间的SQL差异

时间:2020-10-30 19:25:49

标签: mysql sql laravel join difference

场景:
一家每天生产各种尺寸和规格(swg)的钢管的工厂被记录并存储在pipe_production表中(pipe_id是管道表的外键)。工厂还具有定期向其销售管道的客户,根据要求创建发票并将其记录在发票表中。随后,与每个发票相关的管道将存储在pipe_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

1 个答案:

答案 0 :(得分:0)

我假设您只需要对查询进行少量修改,并在您的invoices语句中加入b

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  pi
   JOIN invoices i ON pi.invoice_id = i.id
   WHERE i.authorised = 1
   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