As a follow up on my previous question here: Link
These are my tables:
-----------------------------------
ID | ChapterNo | HitCount | MID
-----------------------------------
1 | 2 | 1000 | 1
2 | 2 | 2000 | 1
3 | 1 | 3000 | 1
4 | 3 | 1000 | 1
5 | 1 | 3500 | 1
-----------------------------------
to archive the result, i tried to use the ff query:
SELECT t1.id, t1.hitcount, t1.chapterno
FROM chapter as t1
WHERE t1.hitcount = (select max(hitcount) from chapter where chapterno = t1.chapterno and `mid` = t1.`mid`)
AND t1.`mid` = '2524'
ORDER BY t1.chapterno DESC
ID | ChapterNo | HitCount |
---------------------------
4 | 3 | 1000 |
2 | 2 | 2000 |
5 | 1 | 3500 |
---------------------------
This query seem to works really fine at first, but in scale, after I import 80,000 records for testing and implementing. I find out that this ran for 30second. A explain shows:
sel_type table type posible_key key keyLen ref rows Extra
PRIMARY t1 ref mid_idx mid_idx 8 const *3289* Using where; Using filesort
PRIMARY chapter ref mid_idx mid_idx 8 m.t1.mid *17* Using where; Using temporary; Using filesort
The result set is 640 rows. Is there any real good way to optimize this for larger table? Since this table and especialy this query will grow more in the future.
Will using procedure in mysql helps any for this query?
Thank you very much
Try this:
This query will benefit from index on(
chapterno,hitcount). Also, from your data(many records with same value ofMID) andEXPLAINoutput, it seems that you don’t need an index onmid(I believemid_idxis an index onmid) because it’s not selective enough…