首页 > 解决方案 > MySQL 上的 SQL 查询优化

问题描述

我有一个执行时间过长的 SQL 查询。我该如何优化它,以便它不会花费太多时间,大约需要 620 秒,这意味着 10 分钟。

| 190543 | root | localhost | ischolar | Query   |  620 | Copying to tmp table                                                                                                 
 
SELECT a.article_id, count(a.article_id) AS views
FROM timed_views_log a
INNER JOIN published_articles pa
    ON (a.article_id = pa.article_id)
WHERE
    a.date BETWEEN date_format(curdate() - interval 1 month,'%Y-%m-01 00:00:00') AND
    date_format(last_day(curdate()-interval 1 month),'%Y-%m-%d 23:59:59')
GROUP BY a.article_id
ORDER BY
    views desc
LIMIT 6, 5;

标签: mysqlsqldatabase

解决方案


如果您使用的是 SQL Server,则可以使用它建议的 sql server 查询执行计划和优化。参考文章 - https://www.sqlshack.com/using-the-sql-execution-plan-for-query-performance-tuning/

您的查询是与 where 子句的连接,因此大多数表中的数据本身很大,请尝试添加索引。


推荐阅读