【发布时间】:2012-10-20 17:33:38
【问题描述】:
我有两张表,它们的结构如下:
CREATE TABLE `metaservice`.`user` (
`id` bigint(18) NOT NULL AUTO_INCREMENT,
`userId` bigint(18) NOT NULL,
`name` varchar(40) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `userId` (`userId`) USING BTREE,
KEY `nameIndex` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
CREATE TABLE `metaservice`.`tweet` (
`id` bigint(18) NOT NULL AUTO_INCREMENT,
`tweetId` bigint(18) NOT NULL,
`reqId` int(8) NOT NULL DEFAULT '0',
`postedTime` datetime NOT NULL,
`body` text NOT NULL,
`userId` bigint(18) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK69A46713BA64537` (`userId`),
KEY `reqId` (`reqId`),
CONSTRAINT `FK69A46713BA64537` FOREIGN KEY (`userId`) REFERENCES `user` (`userId`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
我在下面得到了这个 sql 查询:
select
count(distinct user.name) as c
from
tweet as tweet
inner join
user as user
on tweet.userId=user.userId
and tweet.reqId in (
327774,
215173,
104302,
239188,
317122,
972632,
424187,
644254,
946792,
543258)
tweet 表有 6W 条记录而 user 表有 6w+ 条记录时太慢了 此查询返回结果:60594 in 10.45sec
【问题讨论】:
-
问题大概是'Why' + 'Mysql在使用count(distinct)和join时运行缓慢'
-
您是否检查了两个表中的 ID 列是否有正确的索引?
-
将 IN 子句从 JOIN 移出到 WHERE 有什么不同吗?