【问题标题】:Subtract 2 Columns from different tables从不同的表中减去 2 列
【发布时间】:2019-06-24 15:37:41
【问题描述】:

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

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

第一个表的值 'Amount' 对于每个 id 都是唯一的,第二个表通过外键绑定到第一个表的 id 并具有参数 'Amount_Run',这也取决于 id .数量 = 数量 – Amount_run。知道我做错了什么。

【问题讨论】:

  • 有什么问题?据我所知,您没有指定要从中选择的表,如果您想从其他表中获取,则需要添加->join(),并且您还没有使用->get();获取结果@

标签: php laravel eloquent


【解决方案1】:

如果我正确地理解了你的问题,一个简单的连接然后减去就可以了:

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

【讨论】:

    猜你喜欢
    • 2023-03-31
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    相关资源
    最近更新 更多