laravel嵌套select+mysql

ckocjqey  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(252)

如何使用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();

这不起作用,但到目前为止,这个查询非常接近。
顺便说一句,我用的是Laravel5.6。
谢谢!

dy1byipe

dy1byipe1#

使用 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();
jc3wubiy

jc3wubiy2#

试试这个,但肯定需要编辑

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

相关问题