0

我有这个查询

SELECT COUNT( id ) AS count
FROM members_customer_id_1
WHERE id
IN (

SELECT members_in_group.member_id
FROM members_in_group, member_groups
WHERE members_in_group.member_group_id = member_groups.id
AND member_groups.member_group_category_id =3
GROUP BY members_in_group.member_id
)

对 members_in_group 进行更改时,此查询变得非常非常慢。第一次运行后,一切都很顺利,直到表中的下一次更改。

我怀疑问题出在索引上,所以我给members_in_groups.member_id加了一个索引,但是这只影响了没有对表进行更改的时间。

谁能发现为什么查询会这么慢?

这是我的表结构:

CREATE TABLE IF NOT EXISTS `members_customer_id_1` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) COLLATE latin1_danish_ci NOT NULL DEFAULT '',
  `email` varchar(100) COLLATE latin1_danish_ci NOT NULL DEFAULT '',
  `mobile` bigint(16) NOT NULL,
  `zipcode` varchar(10) COLLATE latin1_danish_ci NOT NULL DEFAULT '',
  `sex` varchar(1) COLLATE latin1_danish_ci NOT NULL DEFAULT '',
  `address` varchar(100) COLLATE latin1_danish_ci NOT NULL DEFAULT '',
  `city` varchar(100) COLLATE latin1_danish_ci NOT NULL DEFAULT '',
  `country_id` int(10) NOT NULL,
  `birthday` date NOT NULL DEFAULT '0000-00-00',
  `disable_welcome_message` int(1) NOT NULL,
  `disable_birthday_message` int(1) NOT NULL,
  `confirmed` int(1) NOT NULL,
  `joined` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `updated` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `deleted` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `origin_type_id` int(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_danish_ci AUTO_INCREMENT=39 ;

CREATE TABLE IF NOT EXISTS `member_groups` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `customer_id` int(11) NOT NULL,
  `name` varchar(100) COLLATE latin1_danish_ci NOT NULL,
  `member_group_category_id` int(11) NOT NULL,
  `hidden` int(1) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_danish_ci AUTO_INCREMENT=568 ;

CREATE TABLE IF NOT EXISTS `members_in_group` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `member_id` int(10) NOT NULL,
  `member_group_id` int(10) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `member_id` (`member_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_danish_ci AUTO_INCREMENT=421609 ;
4

1 回答 1

2

我会尝试这样的事情,这样你就可以利用索引

SELECT COUNT(*) AS count
FROM members_customer_id_1
JOIN members_in_group ON members_customer_id_1.id = members_in_group.member_id
JOIN member_groups ON members_in_group.member_group_id = member_groups.id
WHERE member_groups.member_group_category_id =3

编辑:修改后的查询

于 2012-09-12T13:24:36.577 回答