提问者:小点点

如何优化min-max-orderby查询?


我在Laravel的代码是:

Car::selectRaw('*,
    MIN(car_prices.price) AS min_price,
    MAX(car_prices.price) AS max_price,
    MAX(car_prices.updated_at) AS latest_update')
->leftJoin('car_prices', 'car_prices.car_id', 'cars.id')
->groupBy('car_prices.car_id')
->orderBy('latest_update', 'desc')
->paginate(10);

运行时间很长,直到抛出错误:

超过60秒的最大执行时间

cars表中的记录计数为100,000条,car_prices表中的记录计数为6,000,000条。

我该如何优化它呢? 我应该缓存数据吗? 或者有什么比这更好的查询?


共1个答案

匿名用户

您需要有更好的car表唯一索引latest_update或在查询中删除->orderby('latest_update','desc')。 并在收到结果后对其进行排序

你可以用explain检查mysql中的性能

解释SELECT*FROM car order by latest_update DESC;

///检查以下内容:https://www.exoscale.com/syslog/explainse-mysql-queries/#:~:text=The%20last%20dece.-,Explain,delete%20%2c%20replace%20%2c%20 and%20update%20.

和https://dev.mysql.com/doc/refman/5.7/en/using-explain.html#:~:text=%20explain%20语句%20提供%20information,%2c%20replace%20%2c%20和%20update%20语句。&text=The%20是%2c%20mySQL%20解释%20how,在%20whic%20order中连接了%20和%20。

基本上,你需要优化(更好的索引)你的DB表“车”,使它表现良好

和其他一些事情,您可能会尝试增加php.ini中的执行时间,您需要将max_execution_time设置为600或更多,以检查它需要多少时间来完成执行。 https://www.codewall.co.uk/increge-php-script-max-execution-time-limit-using-ini_set-function/