GROUP BY YEAR & Month 的 MySQL 文件排序

标签 mysql indexing group-by

我有一个大表来存储我的网络应用程序的调试信息。问题是该表现在有 500,000 行,其中一个查询很慢,因为未使用索引。

SQL:

EXPLAIN SELECT count(*) AS `count`, month(event_date) AS `month`, year(event_date) AS `year`FROM events WHERE 1 = 1 GROUP BY year(event_date) DESC, month(event_date) DESC LIMIT 6;

结果:

SIMPLE  events  index   NULL    event_date  8   NULL    139358  Using index; Using temporary; Using file sort

这是表结构。

CREATE TABLE IF NOT EXISTS `events` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Event Primary Key',
`event_number` int(11) NOT NULL,
`user_id` int(11) unsigned NOT NULL COMMENT 'User ID',
`server_id` int(11) unsigned DEFAULT NULL COMMENT 'The ID of the remote log client',
`remote_id` int(11) unsigned DEFAULT NULL COMMENT 'The Event Primary Key from the remote client',
`event_date` datetime NOT NULL COMMENT 'Event Datetime in local timezone',
`event_date_utc` datetime NOT NULL COMMENT 'Event Datetime in UTC timezone',
`event_type` varchar(255) NOT NULL COMMENT 'The type of event',
`event_source` varchar(255) NOT NULL COMMENT 'Text description of the source of the event',
`event_severity` varchar(255) NOT NULL COMMENT 'Notice, Warning etc',
`event_file` text NOT NULL COMMENT 'The full file location of the source of the event',
`event_file_line` int(11) NOT NULL COMMENT 'The line in the file that triggered the event',
`event_ip_address` varchar(255) NOT NULL COMMENT 'IP Address of the user that triggered the event',
`event_summary` varchar(255) NOT NULL COMMENT 'A summary of the description',
`event_description` text NOT NULL COMMENT 'Full description of the event',
`event_trace` text NOT NULL COMMENT 'Full PHP trace',
`event_synced` int(1) unsigned DEFAULT '0',
PRIMARY KEY (`id`),
KEY `event_type` (`event_type`),
KEY `event_source` (`event_source`),
KEY `user_id` (`user_id`),
KEY `server_id` (`server_id`),
KEY `event_date` (`event_date`)
)

如果有人想在没有文件排序的情况下获得相同的结果,那就太棒了!

最佳答案

GROUP BY 隐含 MySQL 中的 ORDER BY

因此尝试添加 ORDER BY NULL:这通常会消除文件排序

参见 "ORDER BY Optimization"在 MySQL 文档中

关于GROUP BY YEAR & Month 的 MySQL 文件排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9428527/

相关文章:

mysql - Liquibase 给出 MySQL 语法错误,而 phpMyAdmin 没有

php - 使用PHPExcel将数据从mysql导出到xls

php - mysql中的双重插入

sql - 死锁使用自引用外键

sql - 将行与排名合并

ios - 核心数据异常错误 - 无效的获取请求 : HAVING with no GROUP BY with userInfo of (null)

mysql - 更新记录总和

MySQL "command out of sync"

mysql - 使用索引语义确定 MySql 索引列中的字段是否为数字

Django:JSONField + 全文搜索 + 索引 -> 序列扫描。如何配置索引工作?