首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用count(distinct)和join优化Mysql

如何使用count(distinct)和join优化Mysql
EN

Stack Overflow用户
提问于 2012-10-31 17:34:13
回答 4查看 216关注 0票数 1

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

代码语言:javascript
复制
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查询如下:

代码语言:javascript
复制
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

EN

回答 4

Stack Overflow用户

发布于 2012-10-31 17:39:31

我建议您使用EXPLAIN如下:

代码语言:javascript
复制
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 Explain Syntax

Optimize Queries with Explain

Using MySQL Explain

MySQL Explain Reference

查看结果后,您需要确定应该对哪些列进行索引。

票数 1
EN

Stack Overflow用户

发布于 2012-10-31 17:41:01

试试这个:

代码语言:javascript
复制
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
票数 0
EN

Stack Overflow用户

发布于 2012-10-31 17:44:43

我建议你给你的键建立索引。索引不仅仅用于主键或唯一键。如果表中有任何列可供搜索,则几乎总是应该对它们进行索引。

另外,请阅读Link

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13154904

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档