Laravel 嵌套选择 + MySQL

2021-12-26 00:00:00 mysql laravel eloquent

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

How can i do a nested select using Laravel raw query?

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

这不起作用,但到目前为止这个查询非常接近.

This is not working, but so far this query is very close.

顺便说一下,我使用的是 Laravel 5.6.

By the way, I am using Laravel 5.6.

谢谢!

推荐答案

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

Use DB::raw() in table() and don't use it in groupBy() and 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();

相关文章