查询:
SELECT DATE(create_time) as createDate, count(url_id)
FROM t_notification
WHERE domain_id = 185
AND type = 12
AND create_time >= '2012-12-15'
GROUP BY createDate
解释
explain select DATE(create_time) as createDate, count(url_id) from t_notification where domain_id = 185 and type = 12 and create_time >= '2012-12-15' group by createDate;
+----+-------------+----------------+------+---------------------------------+----------+---------+-------+---------+----------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+----------------+------+---------------------------------+----------+---------+-------+---------+----------------------------------------------+
| 1 | SIMPLE | t_notification | ref | FK_notification_domain,idx_test | idx_test | 5 | const | 9189516 | Using where; Using temporary; Using filesort |
+----+-------------+----------------+------+---------------------------------+----------+---------+-------+---------+----------------------------------------------+
1 row in set (0.29 sec)
mysql> show create table t_notification\G
*************************** 1. row ***************************
Table: t_notification
Create Table: CREATE TABLE `t_notification` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`type` int(11) DEFAULT NULL,
`content` varchar(512) DEFAULT NULL,
`create_time` date DEFAULT NULL,
`domain_id` int(11) DEFAULT NULL,
`url_id` int(11) DEFAULT NULL,
`status` int(11) DEFAULT NULL,
`targetrul_partnerurl_id` int(11) DEFAULT NULL,
`week_entrances` int(11) DEFAULT NULL COMMENT 'for keyword and target_url',
PRIMARY KEY (`id`),
KEY `url_id` (`url_id`),
KEY `targetrul_partnerurl_id` (`targetrul_partnerurl_id`),
KEY `FK_notification_domain` (`domain_id`,`id`),
KEY `idx_test` (`domain_id`,`status`,`type`,`create_time`)
) ENGINE=InnoDB AUTO_INCREMENT=50747991 DEFAULT CHARSET=utf8
1 row in set (0.00 sec)
答案 0 :(得分:2)
假设您发出以下SELECT语句:mysql>选择 * FROM tbl_name WHERE col1 = val1 AND col2 = val2;
如果col1和col2上存在多列索引,则相应 行可以直接获取。如果存在单独的单列索引 在col1和col2上,优化器将尝试使用索引合并 优化(参见第8.3.1.4节“索引合并优化”)或 尝试通过决定哪个索引来找到最严格的索引 找到更少的行并使用该索引来获取行。
如果表有多列索引,则表示最左边的前缀 优化器可以使用index来查找行。例如,如果你 在(col1,col2,col3)上有一个三列索引,你已编入索引 搜索(col1),(col1,col2)和(col1,col2,col3)的功能。
您在类型或create_time上没有可用的索引。从密钥idx_test中删除状态或在(type,create_time)或类型和create_time上单独创建新索引。
答案 1 :(得分:0)
考虑在 domain_id 和类型列上创建复合索引,因为它们直接在where子句中使用。它肯定会提高查询的性能。