首页 > 解决方案 > 如何组合这 2 个 SQL 查询?

问题描述

我正在尝试组合来自多个表的数据并将其发送到刀片模板。

我试图把total_pricewith ->select('products.name', total_price,但我得到了

语法错误或访问冲突:1055 SELECT 列表的表达式 #2 不在 GROUP BY 子句中,并且包含非聚合列`

$orders = DB::table('orders')
    ->join('order_items', 'order_items.order_id', '=', 'orders.id')
    ->join('customers', 'customers.id', '=', 'orders.customer_id')
    ->join('products', 'products.id', '=', 'order_items.product_id')
    ->select('products.name', DB::raw('SUM(order_items.quantity * order_items.unit_price) as total, SUM(order_items.quantity) as quantity'))
    ->whereYear('orders.created_at', $currentYear)
    ->whereMonth('orders.created_at', $currentMonth)
    ->where('orders.customer_id', $id)
    ->groupBy('order_items.product_id');

$order_prices = DB::table('orders')->select('total_price')->get();

标签: phpmysqllaravel

解决方案


推荐阅读