[英]index_merge full table scan - 2 seconds mysql select
我有這個選擇:
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`),
);
問題是它正在使用全表掃描:
這需要很多時間。 任何想法以獲得更快的結果?
您如何看待該解決方案:
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`),
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.