我有这个选择:
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聊天:
`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`),
);问题是它正在使用全表扫描:

这需要很长时间。有没有更快见效的点子?
发布于 2018-06-22 16:02:07
您对此解决方案有何看法:
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列,您可以轻松地添加它们。
但实际上我认为你的整个数据库模式都是错误的,我认为你需要更多的东西,比如:
`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`),
);也许如果你需要:
`chat` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`message_id` int(11) UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
);https://stackoverflow.com/questions/50982939
复制相似问题