首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MySQL连接/ IN性能优化

MySQL连接/ IN性能优化
EN

Stack Overflow用户
提问于 2015-06-16 15:38:31
回答 2查看 212关注 0票数 0

我有以下MySQL查询:

代码语言:javascript
复制
SELECT 
    p.post_id,
    p.date_created,
    p.description, 
    p.last_edited, 
    p.link, 
    p.link_description, 
    p.link_image_url, 
    p.link_title, 
    p.total_comments, 
    p.total_votes, 
    p.type_id, 
    p.user_id 
FROM posts p JOIN posts_to_tribes ptt ON p.post_id=ptt.post_id 
WHERE ptt.tribe_id IN (1, 2, 3, 4, 5) 
GROUP BY p.post_id 
ORDER BY p.last_edited DESC, p.total_votes DESC LIMIT 25

在非并发环境中,此查询运行~172 In,但在并发环境中运行1-2秒(在性能测试期间)。

解释输出:

posts_to_tribes表的索引:

有什么方法可以提高这里的性能吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-06-16 20:05:14

您需要一个用于posts_to_tribesINDEX(tribe_id, post_id)的复合索引。

GROUP BY是为了补偿JOIN爆炸的行数。这里有一个比IN ( SELECT ... )更好的解决方法

代码语言:javascript
复制
SELECT  p.post_id, p.date_created, p.description, p.last_edited,
        p.link, p.link_description, p.link_image_url, p.link_title,
        p.total_comments, p.total_votes, p.type_id, p.user_id
    FROM  posts p
    JOIN  
      ( SELECT  DISTINCT  post_id
            FROM  posts_to_tribes
            WHERE  tribe_id IN (1, 2, 3, 4, 5)
      ) AS ptt USING (post_id)
    ORDER BY  p.last_edited DESC,
              p.total_votes DESC
    LIMIT  25
票数 1
EN

Stack Overflow用户

发布于 2015-06-16 16:31:02

当您真正想要在两个表之间应用半连接时,您已经应用了一个半连接操作(在INEXISTS谓词中实现了半连接)。

因为您使用了错误的JOIN类型,所以再次使用GROUP BY删除重复记录。这是很多浪费CPU周期的地方。

以下查询要快得多:

代码语言:javascript
复制
SELECT 
    p.post_id,
    p.date_created,
    p.description, 
    p.last_edited, 
    p.link, 
    p.link_description, 
    p.link_image_url, 
    p.link_title, 
    p.total_comments, 
    p.total_votes, 
    p.type_id, 
    p.user_id 
FROM posts p 
WHERE p.post_id IN (
  SELECT ptt.post_id
  FROM posts_to_tribes ptt
  WHERE ptt.tribe_id IN (1, 2, 3, 4, 5)
)
ORDER BY p.last_edited DESC, p.total_votes DESC LIMIT 25

您仍然应该有(p.post_id)(ptt.tribe_id, ptt.post_id)的索引。

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

https://stackoverflow.com/questions/30872163

复制
相关文章

相似问题

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