I’m a beginner to mysql. I have to fetch the most viewed contentid(for the past 120 hours) from the table views. The views table contains 200,000 (lakh) records. I have indexed the contentid column, but my query takes upto 10 sec to fetch the result.
Views table structure is as follows:
contentid viewed ip
155 2011-10-26 00:07:52 216.251.77.226
1150 2011-10-26 00:08:15 65.52.109.72
1134 2011-10-26 00:08:30 178.53.54.221
14 2011-10-26 00:08:49 178.53.54.221
693 2011-10-26 00:08:58 115.184.174.136
433 2011-10-26 00:09:14 66.249.71.138
558 2011-10-26 00:09:26 91.83.214.3
715 2011-10-26 00:16:01 128.171.36.161
226 2011-10-26 00:16:06 110.36.39.102
562 2011-10-26 00:16:51 84.3.173.188
1134 2011-10-26 00:16:53 110.39.67.139
198 2011-10-26 00:16:57 220.227.133.163
155 2011-10-27 05:43:59 64.135.215.142
155 2011-10-27 08:39:46 157.55.39.86
155 2011-10-27 11:23:05 99.55.166.146
155 2011-10-27 15:40:29 174.255.241.202
1150 2011-10-26 00:50:50 119.30.96.83
1150 2011-10-26 01:02:58 66.249.71.138
1150 2011-10-26 08:02:31 95.144.197.55
1132 2011-10-26 00:16:07 119.160.126.99
and my query is
SELECT contentid FROM views
where viewed > DATE_SUB(NOW(), INTERVAL 120 HOUR)
GROUP BY contentid ORDER BY count(contentid ) desc limit 0, 15
I would think that nice indexes for this query would be either a simple index on
viewedor a compound index on(contentid, viewed).You should also change the
COUNT(contentid)toCOUNT(*):