首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >index_merge全表扫描-2秒mysql select

index_merge全表扫描-2秒mysql select
EN

Stack Overflow用户
提问于 2018-06-22 15:35:42
回答 1查看 23关注 0票数 0

我有这个选择:

代码语言:javascript
复制
  SELECT MAX(id) FROM chat
  WHERE (`to` = 1 and `del_to_status` = '0') or (`from` = 1 and `del_from_status` = '0')
  GROUP BY CASE WHEN 1 = `to` THEN `from` ELSE `to` END

聊天:

代码语言:javascript
复制
`chat` (
  `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `from` int(11) UNSIGNED NOT NULL,
  `to` int(11) UNSIGNED NOT NULL,
  `message` text NOT NULL,
  `del_from_status` tinyint(1) NOT NULL DEFAULT '0',
  `del_to_status` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `from` (`from`),
  KEY `to` (`to`),
);

问题是它正在使用全表扫描:

这需要很长时间。有没有更快见效的点子?

EN

回答 1

Stack Overflow用户

发布于 2018-06-22 16:02:07

您对此解决方案有何看法:

代码语言:javascript
复制
select grouped_by_to.user, greatest(grouped_by_to.id, grouped_by_from.id ) from 
(
    select c1.to as user, max(id) as id from chat c1
    group by c1.to 
) grouped_by_to

join
(
    select c1.from as user, max(id) as id from chat c1
    group by c1.from
) grouped_by_from on grouped_by_from.user = grouped_by_to.user

请注意,我忽略了del_to_status列,您可以轻松地添加它们。

但实际上我认为你的整个数据库模式都是错误的,我认为你需要更多的东西,比如:

代码语言:javascript
复制
`messages` (
  `message_id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` int(11) UNSIGNED NOT NULL,
  `message` text NOT NULL,
  `message_date` timestamp NOT NULL,
  PRIMARY KEY (`message_id`),
);

`conversatinos` (
  `conversation_id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `message_id` int(11) UNSIGNED NOT NULL,
  PRIMARY KEY (`conversation_id`),
);

`users` (
  `user_id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_name` int(11) UNSIGNED NOT NULL,
  PRIMARY KEY (`user_id`),
);

也许如果你需要:

代码语言:javascript
复制
`chat` (
  `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `message_id` int(11) UNSIGNED NOT NULL,
  PRIMARY KEY (`id`),
);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50982939

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档