我有这个复杂的查询,我需要优化它。没有索引需要 20 毫秒,我尝试添加一些索引,它更好,现在我有 4 毫秒。但我没有任何经验。你能帮我让它更快吗?
SELECT COUNT(*) FROM(
SELECT user_id FROM times
INNER JOIN tags ON times.user_id = tags.tag_id
INNER JOIN users ON tags.user_nr = users.nr
WHERE (times.time < 1597313)
AND (times.run_id="118")
AND (times.user_id != 109330258)
AND (times.user_id != 0)
AND (times.time != 0 )
AND (times.cell != 1 )
AND (users.category_id="4")
GROUP BY user_id HAVING count(*) == 1
UNION
SELECT user_id FROM times
INNER JOIN tags ON times.user_id = tags.tag_id
INNER JOIN users ON tags.user_nr = users.nr
WHERE (times.run_id="118")
AND (times.user_id != 109330258)
AND (times.user_id != 0 )
AND (times.time != 0 ) AND (times.cell != 1 )
AND (users.category_id="4")
GROUP BY user_id HAVING count(*) > 1
)
我添加了 3 个索引。
- 表格标签 - tagid
- 餐桌时间 - user_id
- 表用户 - nr