Mysql查询与内部子查询和where,order,group不使用索引

时间:2015-08-10 13:06:41

标签: mysql sql optimization database-indexes filesort

所有。 我有2个mysql表类型myisam

CREATE TABLE `users` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

CREATE TABLE `users_ratings` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `created_date` varchar(255) DEFAULT NULL,
  `user_id` mediumint(9) DEFAULT NULL,
  `rating1` mediumint(9) DEFAULT NULL,
  `rating2` mediumint(9) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

可以下载转储here

我希望所有用户都通过rating2选择列表并对rating2进行排序,而rating2必须是> 1000

SELECT * FROM users as u 
INNER JOIN (SELECT rating2, user_id,MAX(created_date) as maxdate FROM `users_ratings` GROUP BY user_id) as x ON x.user_id = u.id 
INNER JOIN users_ratings as ur ON(ur.created_date = x.maxdate and ur.user_id = u.id) 
WHERE x.rating2 > 1000 
ORDER by ur.rating2

如果没有这样的索引,查询将执行9秒。

所有可能的代码,我认为可以将请求的时间减少到1-2秒。

帮助放置索引的权利

1 个答案:

答案 0 :(得分:0)

我怀疑你想要以下查询。假设你这样做,并且性能仍然是一个问题,请提供相同的EXPLAIN ......

(这假设user_id,[rating2,]created_date上的唯一键,实际上未指定)

SELECT u.*
     , x.*
  FROM users u 
  JOIN users_ratings x
    ON x.user_id = u.id
  JOIN 
     ( SELECT user_id
            , MAX(created_date) maxdate 
         FROM users_ratings
        WHERE rating2 > 1000
        GROUP 
           BY user_id
     ) y 
    ON y.user_id = x.user_id 
   AND y.maxdate = x.created_date
 ORDER 
    BY x.rating2;