- 执行查询大约需要 5 到 20 分钟。
- 因此,我们遇到了负载峰值。
- 请帮我重写查询。
- 还帮助我提高了查询的性能。
查询:
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)
最佳答案
来自 MySQl docs
Suppose that you issue the following SELECT statement: mysql> SELECT * FROM tbl_name WHERE col1=val1 AND col2=val2;
If a multiple-column index exists on col1 and col2, the appropriate rows can be fetched directly. If separate single-column indexes exist on col1 and col2, the optimizer will attempt to use the Index Merge optimization (see Section 8.3.1.4, “Index Merge Optimization”), or attempt to find the most restrictive index by deciding which index finds fewer rows and using that index to fetch the rows.
If the table has a multiple-column index, any leftmost prefix of the index can be used by the optimizer to find rows. For example, if you have a three-column index on (col1, col2, col3), you have indexed search capabilities on (col1), (col1, col2), and (col1, col2, col3).
您在类型或 create_time 上没有可用的索引。要么从键 idx_test 中删除状态,要么在 (type, create_time) 上或分别在 type 和 create_time 上创建一个新索引。
关于mysql - 查询需要更多时间来执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14373196/