我有这个选择:
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`),
);
问题在于它正在使用全表扫描:
这需要很多时间。有什么想法可以更快获得结果?
答案 0 :(得分:1)
您如何看待该解决方案:
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`),
);