MySQL 查询耗时 6 秒
MySQL Query taking over 6 seconds
不久前,我得到了一些关于特定查询的帮助。这是 link:
我的查询与此类似:
SELECT event_data, class_40_winner, class_30_winner
FROM events e
LEFT JOIN (SELECT result_event, name AS class_40_winner
FROM results
WHERE class = 40 AND position = 1) c40 ON e.id = c40.result_event
LEFT JOIN (SELECT result_event, name AS class_30_winner
FROM results
WHERE class = 30 AND position = 1) c30 ON e.id = c30.result_event
我现在已经在我的数据库中输入了足够多的数据(22,000 行),这个查询需要 6 秒才能完成。 (我的实际查询比上面的大,因为它现在有 4 个连接。)
我在查询中使用了 "Explain" 函数来查看。来自 "results" table 的每个查询都在提取 22,000 行,所以这似乎是问题所在。
我做了一些研究,听起来我应该能够在 "results" table 上对相关专栏进行索引以帮助加快速度。但是当我这样做时,它实际上将我的查询速度减慢了大约 10 秒。
有什么建议可以改进此查询吗?
试试这个查询:
SELECT
e.event_date,
r1.name as class_40_winner,
r2.name as class_30_winner
FROM
events e,
results r1,
results r2
WHERE
r1.class = 40 AND
r2.class = 30 AND
r1.position = 1 AND
r2.position = 1 AND
r1.result_event = e.id AND
r2.result_event = e.id
SELECT e.event_data
, r.class
, r.name winner
FROM events e
JOIN results r
ON r.result_event = e.id
WHERE class IN (30,40)
AND position = 1
此问题的其余部分是一个简单的显示问题,最好在应用程序代码中解决。
AFAIK,您正在旋转数据,我认为使用 max(case ...) ... group by
在旋转数据方面具有良好的性能。
我可以建议您改用此查询:
select event_date
, max(case when r.class = 40 then name end) `Class 40 Winner`
, max(case when r.class = 30 then name end) `Class 30 Winner`
from events e
left join results r on e.event_id = r.result_event and r.position = 1
group by event_date;
不久前,我得到了一些关于特定查询的帮助。这是 link:
我的查询与此类似:
SELECT event_data, class_40_winner, class_30_winner
FROM events e
LEFT JOIN (SELECT result_event, name AS class_40_winner
FROM results
WHERE class = 40 AND position = 1) c40 ON e.id = c40.result_event
LEFT JOIN (SELECT result_event, name AS class_30_winner
FROM results
WHERE class = 30 AND position = 1) c30 ON e.id = c30.result_event
我现在已经在我的数据库中输入了足够多的数据(22,000 行),这个查询需要 6 秒才能完成。 (我的实际查询比上面的大,因为它现在有 4 个连接。)
我在查询中使用了 "Explain" 函数来查看。来自 "results" table 的每个查询都在提取 22,000 行,所以这似乎是问题所在。
我做了一些研究,听起来我应该能够在 "results" table 上对相关专栏进行索引以帮助加快速度。但是当我这样做时,它实际上将我的查询速度减慢了大约 10 秒。
有什么建议可以改进此查询吗?
试试这个查询:
SELECT
e.event_date,
r1.name as class_40_winner,
r2.name as class_30_winner
FROM
events e,
results r1,
results r2
WHERE
r1.class = 40 AND
r2.class = 30 AND
r1.position = 1 AND
r2.position = 1 AND
r1.result_event = e.id AND
r2.result_event = e.id
SELECT e.event_data
, r.class
, r.name winner
FROM events e
JOIN results r
ON r.result_event = e.id
WHERE class IN (30,40)
AND position = 1
此问题的其余部分是一个简单的显示问题,最好在应用程序代码中解决。
AFAIK,您正在旋转数据,我认为使用 max(case ...) ... group by
在旋转数据方面具有良好的性能。
我可以建议您改用此查询:
select event_date
, max(case when r.class = 40 then name end) `Class 40 Winner`
, max(case when r.class = 30 then name end) `Class 30 Winner`
from events e
left join results r on e.event_id = r.result_event and r.position = 1
group by event_date;