我想将子查询合并到主查询中
这是我的原始查询
select field1, field3, total
from (select field1, field3, sum(field2) as total
from sales
group by field1, field2
having total <> 0
) s
group by field1;
我尝试将其合并
$sub = Sales::select(DB::raw('field1,field3,SUM(field2)as total'))
->groupBy('field1',DB::raw('field3 having total<> 0'));
$main = DB::table(DB::raw("({$sub->toSql()}) as sub") )
->select('field1', 'field3','total');
$main ->mergeBindings($sub->getQuery());
$main ->groupBy('field1');
$main ->get();
但是它不返回任何数据。这怎么了
答案 0 :(得分:0)
我建议使用fromRaw方法:
$finalQuery = self::newQuery()->fromRaw("({$subQuery->toSql()}) as sub")
答案 1 :(得分:0)
如果@DigitalDrifter响应中提到的fromSub方法未使用Laravel 5.6,则只需在pizzas_offered
函数中包含子查询即可
from()