如何进行更快的最大n组查询?

时间:2012-05-22 00:04:21

标签: mysql greatest-n-per-group

我正在使用此查询:

SELECT district, id
FROM adverts ls
GROUP BY district, id
HAVING (

SELECT count( * )
FROM adverts
WHERE district = ls.district
AND id > ls.id
) <5
ORDER BY district, id DESC ;

LIMIT 0 , 30

花了大约35秒。以下是解释:

id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra
1   PRIMARY     ls  range   NULL    i_id    5   NULL    16166   Using index for group-by; Using temporary; Using f...
2   DEPENDENT SUBQUERY  ilan_genel  ref     PRIMARY,i_id,i_ozellik_id,i_tip_fiyat,i_tip_id,i_d...   i_durum_id  2   func    25  Using where; Using index 

有没有办法让它更快?

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT    district, id, COUNT(b.district)
FROM      adverts a INNER JOIN adverts b
              ON a.district = b.district
WHERE     b.id > a.id
GROUP BY  district, id 
HAVING    COUNT(b.district) < 5
ORDER BY  district, id DESC 

根据定义,Joinssubqueries 更快