1

我有两个表,它们的结构如下:

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

4

4 回答 4

1

我建议您按如下方式使用 EXPLAIN:

EXPLAIN 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)

然后分析 EXPLAIN 给你的响应。可以通过以下来源找到有关 MySQL 解释的更多信息:

MySQL解释语法

使用解释优化查询

使用 MySQL 解释

MySQL 解释参考

查看结果后,您需要决定应该索引哪些列。

于 2012-10-31T09:39:31.497 回答
0

我建议你索引你的键。索引不仅仅用于主键或唯一键。如果您要搜索的表中有任何列,您几乎应该始终为它们编制索引。

另请阅读该链接

于 2012-10-31T09:44:42.700 回答
0

尝试这个:

select count(*) as c from (
select
       user.name 
    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)
group by user.name) a
于 2012-10-31T09:41:00.627 回答
0

试试这个——

SELECT
  COUNT(DISTINCT user.name) AS c
FROM
  tweet AS tweet
INNER JOIN user AS user
  ON tweet.userId = user.userId
INNER JOIN (
    SELECT 327774 AS reqId UNION
    SELECT 215173 UNION
    SELECT 104302 UNION
    SELECT 239188 UNION
    SELECT 317122 UNION
    SELECT 972632 UNION
    SELECT 424187 UNION
    SELECT 644254 UNION
    SELECT 946792 UNION
    SELECT 543258
  ) t
  ON tweet.reqId  = t.reqId;
于 2012-10-31T10:20:20.000 回答