gpt4 book ai didi

MySQL : Improving query perfomance on join with order by clause

转载 作者:行者123 更新时间:2023-11-30 23:26:19 26 4
gpt4 key购买 nike

我有两个表,其中包含用户的日常事件。我有两个加入这些表并从此表中选择前十个 ID。

表 1:构建日志

+----------------+------------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+------------------------+------+-----+---------+----------------+
| NAME | varchar(50) | YES | | NULL | |
| ID | int(11) | NO | PRI | NULL | auto_increment |
| DATE_AND_TIME | datetime | YES | | NULL | |
| COMMENT | mediumtext | YES | | NULL | |
+----------------+------------------------+------+-----+---------+----------------+

行数:276186

表 2:报告

+---------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+--------------+------+-----+---------+----------------+
| r_id | int(10) | NO | PRI | NULL | auto_increment |
| id | int(15) | YES | UNI | NULL | |
| label | varchar(200) | YES | | NULL | |
+---------------+--------------+------+-----+---------+----------------+

行数:134058

如果我仅对使用 id 的这两个表使用连接查询,它会非常快。

查询 1:

select  buildlog.id,reports.label from buildlog join reports on reports.id = buildlog.id limit 10\G

查询时间:一组 10 行(0.01 秒)

如果我添加 order by 以获取最新的十个构建 ID,标记它需要 1 到 2 分钟才能执行。

查询 2:

select  buildlog.id,reports.label from buildlog join reports on reports.id = buildlog.id order by buildlog.id desc limit 10\G

查询时间:集合中有 10 行(0.98 秒)

按列排序是一个主键 buildlog.id 。那么,它已经编入索引为什么执行此查询需要更多时间? .谁能建议我如何优化它?

最佳答案

SELECT  * FROM (
SELECT
buildlog.id,
reports.label
FROM
buildlog
JOIN
reports
ON
reports.id = buildlog.id
) AS myval_new
ORDER BY id DESC limit 10

变慢是因为它可能选择在进行连接之前进行排序。在外部查询中执行 order by 会强制它仅对选定的项目进行排序。

关于MySQL : Improving query perfomance on join with order by clause,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13139559/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com