gpt4 book ai didi

mysql - 使用 GROUP BY 时查询速度慢

转载 作者:行者123 更新时间:2023-11-29 12:37:44 25 4
gpt4 key购买 nike

我有以下查询:

SELECT id, user_id, cookieId, text_date 
FROM `_history`
WHERE text_date BETWEEN '2014-09-01' AND '2014-10-01' AND user_id = 1
GROUP BY cookieId
ORDER BY id DESC

我的表架构:

CREATE TABLE `_history` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`cookieId` varchar(50) NOT NULL,
`text_from` varchar(50) NOT NULL,
`text_body` text NOT NULL,
`text_date` datetime NOT NULL,
`aName` varchar(50) NOT NULL,
`hasArrived` enum('0','1') NOT NULL COMMENT,
`agent_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `cookieId` (`cookieId`),
KEY `user_id` (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

EXPLAN 的结果是:

1   SIMPLE  _history    ref cookieId,user_id    user_id 4   const   49837   Using where; Using temporary; Using filesort

有时查询需要 2 秒,有时长达 5 秒。

有什么想法可以让它运行得更快吗?

最佳答案

分组依据目前不执行任何操作,因此请将其删除。

user_id已经有索引了,所以查询和排序就可以了。

text_date 上没有索引,添加索引应该可以加快查询速度。

如果经常出现此查询,请在 user_id 和 text_date 上添加复合索引。

例如。

create index idx_text_date on `_history` (text_date);

根据评论,查询应如下所示:

SELECT cookieId, max(id), max(user_id), max(text_date)
FROM `_history`
WHERE text_date BETWEEN '2014-09-01' AND '2014-10-01'
AND user_id = 1
GROUP BY cookieId
ORDER BY id DESC

索引应该如下所示:

create index idx__history_text_date_cookieId on `_history` (text_date, cookieId);

关于mysql - 使用 GROUP BY 时查询速度慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26523230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com