简体   繁体   中英

index_merge full table scan - 2 seconds mysql select

I have this 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:

`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`),
);

The problem is it is using full table scan:

在此处输入图片说明

it is taking a lot of time. any ideas to get faster results?

What do you think about this solution:

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

Note that i ignored the del_to_status columns, you can add them easily.

But actually I think your whole db schema is wrong, I think you need something more like :

`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`),
);

AND maybe if you need:

`chat` (
  `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
  `message_id` int(11) UNSIGNED NOT NULL,
  PRIMARY KEY (`id`),
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM