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 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3