我有以下需要一段时间才能运行的复杂查询:
SELECT
`User`.`id`,
`User`.`username`,
`User`.`password`,
`User`.`role`,
`User`.`created`,
`User`.`modified`,
`User`.`email`,
`User`.`other_user_id`,
`User`.`first_name`,
`User`.`last_name`,
`User`.`school_id`,
`Resume`.`id`,
`Resume`.`user_id`,
`Resume`.`other_resume_id`,
`Resume`.`other_user_id`,
`Resume`.`file_extension`,
`Resume`.`created`,
`Resume`.`modified`,
`Resume`.`is_deleted`,
`Resume`.`has_file`,
`Resume`.`is_stamped`,
`Resume`.`is_active`
FROM
`dataplace`.`users` AS `User`
LEFT JOIN `dataplace`.`attempts` AS `Attempt`
ON (`Attempt`.`user_id` = `User`.`id` AND `Attempt`.`test_id` != 5)
LEFT JOIN `dataplace`.`resumes` AS `Resume`
ON (`Resume`.`user_id` = `User`.`id`)
WHERE
`Resume`.`has_file` = 1
GROUP BY `User`.`id`
ORDER BY `Attempt`.`score` DESC;
此查询生成以下解释:
+----+-------------+---------+--------+---------------+---------------+---------+------------------------------+-------+----------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------+--------+---------------+---------------+---------+------------------------------+-------+----------------------------------------------+
| 1 | SIMPLE | Resume | ALL | user_id_index | NULL | NULL | NULL | 18818 | Using where; Using temporary; Using filesort |
| 1 | SIMPLE | User | eq_ref | PRIMARY | PRIMARY | 4 | dataplace.Resume.user_id | 1 | Using where |
| 1 | SIMPLE | Attempt | ref | user_id_index | user_id_index | 5 | dataplace.User.id | 1 | |
+----+-------------+---------+--------+---------------+---------------+---------+------------------------------+-------+----------------------------------------------+
resume表有4个独立的索引如下:
PRIMARY id
user_id_index
other_resume_id_index
other_user_id_index
基于此,我希望 resumes 表中的 user_id 索引与相关查询一起使用,但事实并非如此。这可能是订购的问题吗?这个索引没有被使用还有其他原因吗?不同的索引会更好地为我服务吗?我不知道?感谢任何可以提供帮助的人。
最佳答案
您基本上没有有用的 WHERE 子句,因为您的条件适用于最后一个连接的表,并且可以移动到最后一个连接的连接条件中。
Users 表是第一个被访问的表(它在 FROM 子句中被命名为第一个)并且没有针对用户的条件,因此必须访问所有行 - 索引对此无能为力。
关于mysql - 无法使 mysql 使用通过连接查询为表构建的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20251546/