mysql – 在SQL中如何使用索引来加速这个数据库查询?

我有两张桌子:

CREATE TABLE `album` (
  `album_id` int(10) unsigned NOT NULL,
  `artist_id` int(10) unsigned NOT NULL,
  `album_type_id` int(10) unsigned NOT NULL,
  `name` varchar(255) NOT NULL,
  `first_released` year(4) NOT NULL,
  `country_id` smallint(5) unsigned DEFAULT NULL,
  PRIMARY KEY (`album_id`),
  KEY `artist_id` (`artist_id`),
  KEY `name` (`name`)
) ENGINE=InnoDB

CREATE TABLE `artist` (
  `artist_id` int(10) unsigned NOT NULL,
  `type` enum('Band','Person','Unknown','Combination') NOT NULL,
  `name` varchar(255) NOT NULL,
  `gender` enum('Male','Female') DEFAULT NULL,
  `founded` year(4) DEFAULT NULL,
  `country_id` smallint(5) unsigned DEFAULT NULL,
  PRIMARY KEY (`artist_id`),
  KEY `name` (`name`)
) ENGINE=InnoDB;

我的第一个问题:

select ar.name, count(*)   
from artist ar 
join album al on ar.artist_id=al.artist_id   
group by ar.artist_id  
limit 10;

产生0.00秒的结果集.

我想订购结果,所以我添加“order by 2 desc”:

select ar.name, count(*)  
from artist ar  
join album al on ar.artist_id=al.artist_id  
group by ar.artist_id  
order by 2 desc  
limit 10;

但现在结果集超过5秒,这太慢了.

执行计划:

如何添加索引以加快我的新查询?

样本数据:http://bit.ly/1k5ROrT

最佳答案 首先,您应该使用索引列进行选择和计数,这将按性能进行更好的排序,然后您可以在筛选结果上加入艺术家名称以完成数据.有点像.

SELECT ar2.name, t.c
FROM
(
  SELECT ar.artist_id, COUNT(*) c 
  FROM artist ar  
  JOIN album al ON ar.artist_id=al.artist_id  
  GROUP BY ar.artist_id  
  ORDER BY 2 DESC 
  LIMIT 10
)
t JOIN artist ar2 ON ar2.artist_id=t.artist_id  

我尝试使用您的数据,只需不到1秒.希望这有帮助

点赞