laravel 5中的自定义查询

时间:2017-08-04 10:51:27

标签: mysql laravel phpmyadmin query-builder laravel-query-builder

如何在laravel 5.4中运行此类查询

     select items.id,items.name,total,region from items LEFT OUTER JOIN
     (select  purchases.region_id as region , sum(purchases_detail.quantity) 
     as total,purchases_detail.item_id
     from purchases_detail
     left join purchases on(purchases.id=purchases_detail.purchase_id)
     GROUP BY purchases_detail.item_id) pd on (pd.item_id=items.id)

当我在DB :: select('')中尝试这个时 它给了我一个错误:

  

SQLSTATE [42000]:语法错误或访问冲突:1055'amsdb.purchases.region_id'不在GROUP BY中(SQL:select items.id,items.name,total,items from LEFT OUTER JOIN   (选择purchases.region_id作为区域,sum(purchases_detail.quantity)为total,purchases_detail.item_id   来自purchases_detail   离开加入购买(purchases.id = purchases_detail.purchase_id)   GROUP BY purchases_detail.item_id)pd on(pd.item_id = items.id))

但是当我运行Phpmyadmin

时效果很好

2 个答案:

答案 0 :(得分:0)

正如错误消息所示,purchases.region_id列不会显示为聚合,也不会按其进行分组。快速解决方法是从内部和外部查询中删除此列:

SELECT
    items.id,
    items.name,
    pd.total
FROM items
LEFT JOIN
(
    SELECT
        t1.item_id,
        SUM(t1.quantity) AS total
     FROM purchases_detail t1
     LEFT JOIN purchases t2
         ON t2.id = t1.purchase_id
     GROUP BY t1.item_id
) pd
     ON pd.item_id = items.id

答案 1 :(得分:0)

Not sure, but I think that the select() method cannot contain all your SQL query.

I don't know if it will work, but try this one. It uses many query builder functions:

$subQuery = DB::table('purchases_detail')
    ->select(DB::raw('purchases.region_id as region , sum(purchases_detail.quantity) 
     as total,purchases_detail.item_id'))
    ->leftJoin('purchases', 'purchases.id', '=', 'purchases_detail.purchase_id')
    ->groupBy('purchases_detail.item_id')
    ->toSql();

$result = DB::table('items')
    ->select('items.id', 'items.name', 'total,region')
    ->leftJoin($subQuery . ' pd', 'pd.item_id', '=', 'items.id') // if not working, try ->leftJoin(DB::raw($subQuery) . ' pd', 'pd.item_id', '=', 'items.id')
    ->get();

Since your query has a nested SELECT, you have to make it in two times.