减去不同表中的2列 [英] Subtract 2 Columns from different tables

查看:37
本文介绍了减去不同表中的2列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试建立一个查询,其中减去了来自不同表的2列.这是我尝试过的:

I'm trying to build a query where 2 columns from different tables get subtracted. This is what I tried:

DB::connection('lab_inv')->where('tab2'.'Amount_Run', '=', 'tab1'.'Amount')->selectraw('tab1.Amount - tab2.Amount_Run');

第一个表的值'Amount'对于每个id都是唯一的,第二个表由外键绑定到第一个表的id,并且参数'Amount_Run'随ID的不同而不同.金额=金额–金额运行.知道我在做什么错了.

The first table has the value ‘Amount’ which is unique for each id, the second table is bound by a foreign key to the id of the first table and has the parameter ‘Amount_Run’ which is also different depending on the id. Amount = Amount – Amount_run. Any Idea what I’m doing wrong.

推荐答案

如果我正确理解了您的问题,那么简单的联接然后减去就可以解决问题:

If i understood your question correctly, a simple join and then subtract would do the trick:

DB::connection('lab_inv')
    ->table('tab1')
    ->join('tab2', 'tab1.id', 'tab2.tab1_id') // replace this with the actual foreign key 
    ->selectraw('tab1.Amount - tab2.Amount_Run AS amount')
    ->get(); 

这篇关于减去不同表中的2列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆