删除子查询以提高性能

时间:2016-03-23 11:23:51

标签: mysql

以下查询非常慢,很可能是子查询

SELECT * 
FROM releases
INNER JOIN release_artists ON release_artists.release_id = releases.id
WHERE release_artists.artists IN (SELECT release_artists.artists
                                  FROM release_artists
                                  INNER JOIN charts_extended ON charts_extended.release_id = release_artists.release_id
                                  WHERE charts_extended.artist = 'Quickinho'
                                  GROUP BY release_artists.artists)
GROUP BY releases.id
ORDER BY releases.date DESC
LIMIT 0,60

charts_extended.artist有大约2500条记录,所以这不应该花那么长时间。我可以使用什么而不是子查询?

EXPLAIN给出了

1   PRIMARY releases    index   PRIMARY date    82  NULL    60  Using temporary
1   PRIMARY release_artists ref release_id  release_id  4   soundshe.releases.id    1   Using where; Using index
2   DEPENDENT SUBQUERY  charts_extended ref artist_2,release_id,artist  artist_2    82  const   2472    Using where; Using index; Using temporary; Using filesort
2   DEPENDENT SUBQUERY  release_artists ref release_id  release_id  4   soundshe.charts_extended.release_id 1   Using index

下面的表DESC

charts_extended

id  int(11) NO  PRI NULL    auto_increment
artist  varchar(80) NO  MUL NULL    
url text    NO      NULL    
release_id  int(11) NO  MUL NULL    
date    varchar(50) NO      NULL    
type    varchar(4)  NO      NULL    
source  varchar(3)  NO      NULL    

释放

id  int(11) NO  PRI NULL    
artist  varchar(255)    NO  MUL NULL    
all_artists varchar(200)    NO  MUL NULL    
format  varchar(80) NO  MUL NULL    
title   varchar(255)    NO  MUL NULL    
label   varchar(255)    NO  MUL NULL    
label_no_country    varchar(255)    NO  MUL NULL    
link    text    NO      NULL    
genre   varchar(50) NO  MUL NULL    
date    varchar(80) NO  MUL NULL    
image   text    NO      NULL    
favourite   varchar(1)  NO      NULL    
time    varchar(20) NO      NULL    
category    varchar(30) NO  MUL NULL    
format_category varchar(20) NO  MUL NULL    
display varchar(1)  NO      NULL    
image_stored    varchar(1)  NO      NULL

release_artists

id  int(11) NO  PRI NULL    auto_increment
release_id  int(10) NO  MUL NULL    
artists varchar(100)    NO      NULL    

1 个答案:

答案 0 :(得分:2)

您的子查询加入了release_artists,但您的外部查询也是如此,这是不寻常的。看起来你想要发布艺术家的60个最新版本,图表扩展arist是Quickinho。如果我正确理解了查询,我根本不认为你需要一个子查询。

我会尝试

SELECT * FROM releases
INNER JOIN release_artists
ON release_artists.release_id=releases.id
INNER JOIN charts_extended
ON charts_extended.release_id=release_artists.release_id
WHERE charts_extended.artist='Quickinho'
GROUP BY releases.id
ORDER BY releases.date DESC
LIMIT 0,60

您还没有提供有关图表扩展表的大量信息,但是如果您获得重复项,因为每个发布艺术家有上述n行,您可以通过调整您的组或使用不同的等来删除重复项