我正在尝试改进表中大约有 2000 万行的数据库的查询时间:
下面是我正在运行的查询
`select DATE(timestamp) as timestamp, count(id) as authentications, count(distinct userid) as unique_users from `logs` where `org_id` = '54' and `timestamp` between '2016-09-14 09:00:00' and '2017-08-21 09:37:59' group by DATE(timestamp) order by `timestamp` asc`
查询大约需要 20-30 秒才能完成(特定的 org id
有大约 6-700 万条记录)
根据分析器,它花费 95% 的时间对结果进行排序。
我也有一个正在使用的索引(请参阅下面的解释):
1 个简单的日志
ref by_org_id_and_timestamp,org_id by_org_id_and_timestamp 4 const 6231240 Using index condition; Using where; Using filesort
表结构为:
id int(10) unsigned NO PRI auto_increment
org_id int(11) NO MUL
profile varchar(256) NO
linehash varchar(50) NO UNI
timestamp datetime NO
userid varchar(256) NO
server_id varchar(1024) NO
access_id int(11) NO
关于为什么要花这么长时间或者 20-30 秒是我要得到的最佳时间有什么想法吗?
感谢您的关注(希望您能提供帮助!)
------ 显示创建表日志 ------
id int(10) unsigned NOT NULL AUTO_INCREMENT,
org_id int(11) 不为空,
配置文件 varchar(256) 整理 utf8_unicode_ci NOT NULL,
linehash varchar(50) 整理 utf8_unicode_ci NOT NULL,
时间戳日期时间不为空,
userid varchar(256) 整理 utf8_unicode_ci NOT NULL,
server_id varchar(1024) 整理 utf8_unicode_ci NOT NULL,
access_id int(11) 不为空,
主键(id),
唯一键 logs_linehash_unique (linehash),
KEY by_org_id_and_timestamp (org_id,timestamp),
KEY org_id (org_id),
KEY by_org_id_and_timestamp_userid (org_id,timestamp,userid(255))
最佳答案
除了询问索引,我会将您的“count(id)”更改为“count(*)”。
我也会在你的 table 上有一个覆盖索引......
(组织 ID、时间戳、用户 ID)
覆盖您的 where 条件的 org_id 和时间戳。让“userID”随行将有助于您的计数(不同),并且在索引中包含所有部分,引擎不必转到原始数据页面来获取任何其他值。因此它可以直接从索引处理您的查询。
关于php - 在大型数据集上使用 orderby 时 MySQL 查询花费的时间太长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45796319/