A
A
Alexander Kovalchuk2019-01-25 16:37:42
MySQL
Alexander Kovalchuk, 2019-01-25 16:37:42

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.*')

I make this selection with pagination and laravel for pagination takes a request from count, and here's the problem, with this subquery, the execution time for count is about 8c, and if I put a number instead of a subquery, then
the query time becomes 4ms, the question is how can I speed up the query? Perhaps you can do without a subquery? is it possible to throw a subquery into count but use it in the selection? or another way?
this is what the query looks like in SQL
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

1 answer(s)
M
Maxim Fedorov, 2019-01-25
@mamut

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

that is, we get a table in the form order:
maximum_priority and the resulting table with orders, sorting by the received priority

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question