I have the following table:

CREATE TABLE history (
  id int(10) unsigned NOT NULL auto_increment,
  time_sec int(10) unsigned NOT NULL default '0',
  account_id int(10) unsigned NOT NULL default '0',
  PRIMARY KEY  (id),
  KEY account_id (account_id),
  KEY time_sec (time_sec),
) TYPE=MyISAM AUTO_INCREMENT=36653 ;


I need to know which months have activity for any given account_id. Here is my query (which does give me exactly the data I need, albeit slowly):


------------------------------------------------------------------------ ------
SELECT date_format(FROM_UNIXTIME(history.time_sec), '%Y%m') AS month
FROM history
WHERE history.account_id = 216
GROUP BY month
ORDER BY history.time_sec DESC

Showing rows 0 - 5 (6 total, Query took 0.1818 sec)
------------------------------------------------------------------------ ------


The problem is speed. 0.1818 seconds to fetch six rows is too slow. The account in question has about 6000 rows. And there are a total of about 25000 rows in the table. I've at least figured out that the thing that there are two things slowing this down: the WHERE and GROUP BY. E.g., if I drop the WHERE clause (fetch rows for all accounts):


------------------------------------------------------------------------ ------
SELECT date_format(FROM_UNIXTIME(history.time_sec), '%Y%m') AS month
FROM history
GROUP BY month
ORDER BY history.time_sec DESC

Showing rows 0 - 14 (15 total, Query took 0.0930 sec)
------------------------------------------------------------------------ ------


...it's about twice as fast (or half as slow :-) And If I drop the GROUP BY, e.g.:

------------------------------------------------------------------------ ------
SELECT date_format(FROM_UNIXTIME(history.time_sec), '%Y%m') AS month
FROM history
ORDER BY history.time_sec DESC

Showing rows 0 - 29 (23895 total, Query took 0.0008 sec)
------------------------------------------------------------------------ ------


Then it's very fast. Do you guys—and girls!—have any suggestions about how to speed this up, besides adding indices on time_sec and account_id (which I've done)? Thanks for taking a look.

...Rene

Reply via email to