Subtract 2 Columns from different tables

泪湿孤枕 提交于 2021-01-29 08:47:57

问题


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');

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.


回答1:


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(); 


来源:https://stackoverflow.com/questions/54456128/subtract-2-columns-from-different-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!