Subtract 2 Columns from different tables

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.


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

    ->join('tab2', '', 'tab2.tab1_id') // replace this with the actual foreign key 
    ->selectraw('tab1.Amount - tab2.Amount_Run AS amount')

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x