如何使用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。
谢谢!
答案 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();