duandaotui5633 2018-10-03 14:48
浏览 423
已采纳

mysql从另一个select查询值中减去一个select查询

I have two mysql table and I have build to select query using this two tables, both query output is a summation of quantity from inventory_transfer_details table. I need to subtract "total_to" from "total_from". please check below is mysql tables.

Inventory_transfer enter image description here

inventory_transfer_details enter image description here

below is my two queries.

First query:

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'

second query:

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'

I need to subtract from query transfer_to to transfer_from

can you have any guide to convert this final query to laravel query?

  • 写回答

2条回答 默认 最新

  • doulian4467 2018-10-03 14:59
    关注

    You can combine those queries and get the difference

    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'
    

    In the laravel query builder, this query might look like

    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条)

报告相同问题?

悬赏问题

  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测