Answer the question
In order to leave comments, you need to log in
How to speed up join paginate with subquery?
I have a table orders and a relationship with waypoints hasMany the selection needs to be sorted by the date of the point with the highest priority, I made such a query
$query->join('waypoints', function ($join) {
$join->on('orders.id', '=', 'waypoints.order_id')
->whereRaw("waypoints.priority = (select waypoints.priority from waypoints where orders.id = waypoints.order_id order by waypoints.priority desc limit 1)");
})->orderBy('waypoints.date', 'desc')->select('waypoints.date', 'orders.*')
select
count(*) as aggregate
from
`orders`
inner join `waypoints` on `orders`.`id` = `waypoints`.`order_id`
and waypoints.priority = (
select
waypoints.priority
from
waypoints
where
orders.id = waypoints.order_id
order by
waypoints.priority desc
limit
1
)
Answer the question
In order to leave comments, you need to log in
SELECT o.*, w.priority
FROM orders o
LEFT JOIN (
SELECT order_id, max(priority) as priority
FROM waypoints
GROUP BY order_id
) w ON o.id= w.order_id
ORDER BY w.priority desc
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question