Laravel嵌套选择+ MySQL

时间:2018-07-30 10:53:00

标签: mysql laravel eloquent

如何使用Laravel原始查询进行嵌套选择?

SELECT day_of_week, AVG(order_count) average_order FROM 
(
  SELECT DAYNAME(order_date) day_of_week, 
         DAYOFWEEK(order_date) day_num, 
         TO_DAYS(order_date) date,
         count(*) order_count
  FROM orders 
  GROUP BY date
) temp
GROUP BY day_of_week 
ORDER BY day_num

这是我到目前为止尝试过的:

DB::table('(
              SELECT DAYNAME(order_date) day_of_week, 
                     DAYOFWEEK(order_date) day_num, 
                     TO_DAYS(order_date) date,
                     count(*) order_count
              FROM orders 
              GROUP BY date
            ) temp')
            ->select(DB::raw('day_of_week, AVG(order_count) average_order'))
            ->groupBy(DB::raw('day_of_week'))
            ->orderBy(DB::raw('day_num'))
            ->get();

这不起作用,但是到目前为止,该查询非常接近。

顺便说一句,我正在使用Laravel 5.6。

谢谢!

2 个答案:

答案 0 :(得分:2)

DB::raw()中使用table(),不要在groupBy()orderBy()中使用它:

DB::table(DB::raw('(
      SELECT DAYNAME(order_date) day_of_week, 
             DAYOFWEEK(order_date) day_num, 
             TO_DAYS(order_date) date,
             count(*) order_count
      FROM orders 
      GROUP BY date
    ) temp'))
    ->select('day_of_week', DB::raw('AVG(order_count) average_order'))
    ->groupBy('day_of_week')
    ->orderBy('day_num')
    ->get();

您也可以使用fromSub()

$from = DB::table('orders')
    ->selectRaw(
        'DAYNAME(order_date) day_of_week,
        DAYOFWEEK(order_date) day_num, 
        TO_DAYS(order_date) date,
        count(*) order_count'
    )->groupBy('date');
DB::query()->fromSub($from, 'temp')
    ->select('day_of_week', DB::raw('AVG(order_count) average_order'))
    ->groupBy('day_of_week')
    ->orderBy('day_num')
    ->get();

答案 1 :(得分:0)

尝试一下, 但肯定需要编辑

DB::table('orders')
    ->select(DB::raw('(SELECT order_date AS day_of_week, order_date AS day_num, order_date AS date FROM orders GROUP BY date)'))
    ->groupBy(DB::raw('day_of_week'))
    ->orderBy(DB::raw('day_num'))
    ->get();