我有两个mysql表,并且已经建立了使用这两个表选择查询的方法,两个查询输出都是来自stock_transfer_details表的数量的总和。我需要从“ total_from”中减去“ total_to”。请检查以下是mysql表。
下面是我的两个查询。
第一个查询:
select sum(b.transfer_quantity) as total_to
from inventory_transfers as a
join inventory_transfer_details as b on a.id = b.inventory_transfer_id
where a.status="approved" and b.inventory_or_composite_id = '1' and a.to_warehouse_id = '2'
第二次查询:
select sum(b.transfer_quantity) as total_from
from inventory_transfers as a
join inventory_transfer_details as b on a.id = b.inventory_transfer_id
where a.status="approved" and b.inventory_or_composite_id = '1' and a.from_warehouse_id = '2'
我需要从查询transfer_to减去to transfer_from
您是否有任何指南将最终查询转换为laravel查询?
答案 0 :(得分:4)
您可以结合使用这些查询并获得不同之处
SELECT
sum(
IF(a.to_warehouse_id = '2', b.transfer_quantity, 0)
) - sum(
IF(a.from_warehouse_id = '2', b.transfer_quantity, 0)
) as total
FROM
inventory_transfers AS a
JOIN inventory_transfer_details AS b ON a.id = b.inventory_transfer_id
WHERE
a.status = "approved"
AND b.inventory_or_composite_id = '1'
在laravel查询构建器中,该查询可能类似于
DB::table('inventory_transfers as a')
->select(DB::raw('sum(IF(a.to_warehouse_id = '2', b.transfer_quantity, 0)) - sum(IF(a.from_warehouse_id = '2', b.transfer_quantity, 0)) as total'))
->join('inventory_transfer_details as b', DB::raw('a.id'), '=', DB::raw('b.inventory_transfer_id'))
->where([
['a.status', '=', 'approved']
['b.inventory_or_composite_id', '=', 1]
])
->get()
答案 1 :(得分:1)
我想为这个问题提供一个更通用的答案:从任何其他SUM()
中减去任何SUM()
。你可以简单地做...
SELECT Total1, Total2, Total1 - Total2
FROM
(SELECT SUM(id) Total1 FROM TableA) AS a
INNER JOIN
(SELECT SUM(id) Total2 FROM TableB) AS b;
在您的情况下,两个a
和b
子查询将被替换为当前用于计算总和的两个查询。