- 论坛徽章:
- 0
|
向各位请教个mysql查询优化。
有2个表:
DROP TABLE IF EXISTS apchistory;
CREATE TABLE apchistory (
ContextID bigint(20) NOT NULL default '0',
Label char(64) NOT NULL default '',
AlarmLevel char(40) NOT NULL default '',
PRIMARY KEY (ContextID,Label)
) TYPE=MyISAM;
有 10651729 条记录。
DROP TABLE IF EXISTS contexthistory;
CREATE TABLE contexthistory (
ContextID bigint(20) NOT NULL auto_increment,
StopEventTime char(16) NOT NULL default '',
dcqualityvalue double default NULL,
PRIMARY KEY (ContextID),
KEY HistoryIDIndex (HistoryID),
KEY StrategyID (StrategyID),
KEY StopEventTimeIndex (StopEventTime)
) TYPE=MyISAM;
有 1292043 条记录
使用的查询语句:
mysql> select count(distinct (contexthistory.contextid))
-> from contexthistory,apchistory
-> where contexthistory.contextid = apchistory.contextid
-> and alarmlevel > 0
-> and StopEventTime > 20080531000059
-> and StopEventTime < 20080601000059
-> and dcqualityvalue > 0;
+--------------------------------------------+
| count(distinct (contexthistory.contextid)) |
+--------------------------------------------+
| 124751 |
+--------------------------------------------+
1 row in set (1 min 37.73 sec)
耗时1分37秒
explain:
mysql> explain select count(distinct (contexthistory.contextid))
-> from contexthistory,apchistory
-> where contexthistory.contextid = apchistory.contextid
-> and alarmlevel > 0
-> and StopEventTime > 20080531000059
-> and StopEventTime < 20080601000059
-> and dcqualityvalue > 0;
+----+-------------+----------------+--------+----------------------------+---------+---------+--------------------------+----------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+----------------+--------+----------------------------+---------+---------+--------------------------+----------+-------------+
| 1 | SIMPLE | apchistory | ALL | PRIMARY | NULL | NULL | NULL | 10651729 | Using where |
| 1 | SIMPLE | contexthistory | eq_ref | PRIMARY,StopEventTimeIndex | PRIMARY | 8 | pcb.apchistory.ContextID | 1 | Using where |
+----+-------------+----------------+--------+----------------------------+---------+---------+--------------------------+----------+-------------+
2 rows in set (0.03 sec)
这个查询该如何优化呢? 表的索引是可以修改的,但结构不能修改。 |
|