haohan
haohan

Reputation: 91

How to partition this table

This is my table

CREATE TABLE IF NOT EXISTS `results_stock_all` (
  `Result_Id` varchar(50) NOT NULL,
  `Stock_Date` date NOT NULL,
  `Stock_Code` varchar(20) NOT NULL,
  `Prev_Close` float(10,3) NOT NULL DEFAULT '0.000',
  `Open` float(10,3) NOT NULL DEFAULT '0.000',
  `Close` float(10,3) NOT NULL DEFAULT '0.000',
  `High` float(10,3) NOT NULL DEFAULT '0.000',
  `Low` float(10,3) NOT NULL DEFAULT '0.000',
  `Volume` int(11) NOT NULL DEFAULT '0',
  `Change` float(10,3) NOT NULL DEFAULT '0.000',
  `Change_Percent` float(10,3) NOT NULL
  PRIMARY KEY (`Result_Id`),
  KEY `Stock_Date` (`Stock_Date`),
  KEY `Stock_Code_Stock_Date` (`Stock_Code`,`Stock_Date`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

3,150,236 rows, MYISAM, data size: 255.1MB, index size: 209.5MB, Stock_Code: 1468

I have 2 type of query that use often,

1) SELECT cols FROM results_stock_all WHERE Stock_Date = '2011-08-06' ORDER BY cols;

(No problem, pretty fast)

2) SELECT cols FROM results_stock_all WHERE Stock_Code = '1234' ORDER BY Stock_Date DESC LIMIT 3000;

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE  results_stock_all   ref Stock_Code_Stock_Date   Stock_Code_Stock_Date   22  const   5173    Using where

I need to query latest 3000 rows and send the results to charting software. But this query takes about 17 secs at first run for each different Stock_Code.

How to make it faster ? I am thinking to partition this table, but I really don't have idea how to do it , by Date or by Stock_Code ?

If partition by Stock_Code, I believe it will speed up query #2, then how about query #1

Thanks.

EDITED

I tried to add an index Stock_Code, it is faster in this query

SELECT cols FROM results_stock_all WHERE Stock_Code = '1234' ORDER BY Stock_Date DESC LIMIT 3000;

but when i tried to run on smaller results set,

mysql> set session query_cache_type = 0;

mysql> select * from results_stock_all ignore index(stock_code) where stock_code = '1234' order by stock_date desc; 100 rows in set (0.00 sec)

mysql> select * from results_stock_all ignore index(stock_code_stock_date) where stock_code = '1234' order by stock_date desc limit 100; 100 rows in set (0.02 sec)

I believe using where is faster than using file sort.

Upvotes: 1

Views: 227

Answers (1)

Māris Kiseļovs
Māris Kiseļovs

Reputation: 17285

Indexes are used for WHERE, but not for ORDER. So you need to add index for Stock_Code only:

alter table results_stock_all add index `Stock_Code` (`Stock_Code`);

This should make your query much faster.

Upvotes: 1

Related Questions