我有这个问题
SELECT
shot.hole AS hole,
shot.id AS id,
(SELECT s.id FROM shot AS s
WHERE s.hole = shot.hole AND s.shot_number > shot.shot_number AND shot.round_id = s.round_id
ORDER BY s.shot_number ASC LIMIT 1) AS next_shot_id,
shot.distance AS distance_remaining,
shot.type AS hit_type,
shot.area AS onto
FROM shot
JOIN course ON shot.course_id = course.id
JOIN round ON shot.round_id = round.id
WHERE round.uID = 78
这会在大约 0.7 秒内返回 900~ 行。这很好,但是需要更多这样的行
(SELECT s.id FROM shot AS s
WHERE s.hole = shot.hole AND s.shot_number > shot.shot_number AND shot.round_id = s.round_id
ORDER BY s.shot_number ASC LIMIT 1) AS next_shot_id,
例如
(SELECT s.id FROM shot AS s
WHERE s.hole = shot.hole AND s.shot_number < shot.shot_number AND shot.round_id = s.round_id
ORDER BY s.shot_number ASC LIMIT 1) AS past_shot_id,
添加它会将加载时间增加到 10 秒,这太长了,页面通常根本不会加载,或者 MySQL 只是锁定,使用 show processlist
显示查询只是坐在那里发送数据
。
删除这些子查询中的 ORDER BY s.shot_number ASC
子句可将查询时间减少到 0.05 秒,这要好得多。但是需要 ORDER BY
来确保返回下一行或过去的行(镜头),而不是任何旧的随机行。
如何改进此查询以使其运行得更快并返回相同的结果。也许my approach获取下一行和上一行的方法不是最优的,我需要寻找一种不同的方法来返回下一行和上一行 ID?
编辑 - 附加背景信息
查询在我的测试域(一个子域)上没有问题。但是当移动到实时域时,问题就开始了。几乎没有任何改变,但由于这些新的缓慢查询,整个站点都停止了。重点说明:
- 不同域
- /var/www 中的不同文件夹
- 相同的数据库
- 相同的数据库凭据
- 相同的代码
- 添加索引以尝试修复 - 这没有帮助
这些会影响加载时间吗?
最佳答案
这将在一分钟内被标记为“不是答案”,但它说明了一个可能的解决方案,而不是简单地把它放在盘子里交给你....
SELECT * FROM ints;
+---+
| i |
+---+
| 0 |
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
+---+
SELECT x.i, MIN(y.i) FROM ints x LEFT JOIN ints y ON y.i > x.i GROUP BY x.i;
+---+----------+
| i | MIN(y.i) |
+---+----------+
| 0 | 1 |
| 1 | 2 |
| 2 | 3 |
| 3 | 4 |
| 4 | 5 |
| 5 | 6 |
| 6 | 7 |
| 7 | 8 |
| 8 | 9 |
| 9 | NULL |
+---+----------+
关于mysql - 改进此 MySQL 查询 - 选择为子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18099683/