MySQL查询速度慢,顺序为+ group by

时间:2013-01-14 11:37:57

标签: mysql

我有以下查询,因为添加了ORDER BY子句后执行缓慢。 GROUP BYORDER BY的组合似乎存在一些问题,但我不确定从哪里开始优化。 groups表当前有大约100k行,并且连接中使用的所有id都被编入索引。

SELECT groups.name,groups.account_id,groups.description,groups.id, GROUP_CONCAT(DISTINCT categories.name) as cat, GROUP_CONCAT(DISTINCT group_tags.name) as tag
FROM groups 
LEFT JOIN group_categories ON groups.id = group_categories.group_id
LEFT JOIN categories ON group_categories.cat_id = categories.id
LEFT JOIN group_tags ON groups.id = group_tags.group_id
GROUP BY groups.id
ORDER BY case when groups.account_id = 0 then 1 else 0 end, groups.name

EXPLAIN输出:

SIMPLE  groups              index   NULL        PRIMARY     4    NULL                       100843  Using temporary; Using filesort
SIMPLE  group_categories    ref     group_id    group_id    4    groups.id                  1   
SIMPLE  categories          eq_ref  PRIMARY     PRIMARY     4    group_categories.cat_id    1   

创建表格

CREATE TABLE `groups` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `account_id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `description` text NOT NULL,
  `last_updated` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `email` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `accountid` (`account_id`),
  KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=109850 DEFAULT CHARSET=utf8;

0 个答案:

没有答案