本文介绍了Laravel 嵌套选择 + MySQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用 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();
这篇关于Laravel 嵌套选择 + MySQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!