如何优化相关的mysql子查询?在laravel

时间:2016-12-30 04:05:16

标签: mysql laravel

我在Laravel项目中有2个表

1)汽车(身份证,代币,姓名)

2)跟踪(id,car_id,lat,lng,point_time)

跟踪表包含汽车的所有GSP数据并包含大量数据!

我需要获取每辆车的最后跟踪数据。

SELECT distinct `a`.`id` ,
                ( SELECT MAX(`tracking`.`point_time`)
                FROM `tracking`
                WHERE tracking.car_id = a.id ) as `last_time`
FROM `cars` AS `a`

目前,此查询工作正常但需要大约4秒才能执行!

我需要更换查询才能更快地运行。

如上所述,我更喜欢执行原始SQL查询以更快地执行。

2 个答案:

答案 0 :(得分:4)

将子查询(O(n^2))转换为如下连接:

select c.id,
    t.`last_time`
from `cars` c
left outer join (
    select car_id,
        MAX(t.`point_time`) `last_time`
    from `tracking` t
    group by car_id
    ) t on c.id = t.car_id;

答案 1 :(得分:0)

我认为MAXGROUP BY不是很好,仅使用order by,您也应该在 last_time 上添加index,尝试这样:

SELECT DISTINCT r.*
FROM 
( 
    SELECT c.id, t.last_time
    FROM cars AS c 
    LEFT JOIN tracking as t
    ON t.car_id = c.id
    ORDER BY c.id, t.last_time DESC
) AS r