我有两个表,它们的结构如下:
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+条记录时太慢了这个查询在10.45秒内返回结果:60594