【问题标题】:How can I optimize this slow query with multiple joins and sub queries如何使用多个连接和子查询优化这个慢查询
【发布时间】:2014-09-08 14:36:53
【问题描述】:

我必须优化别人编写的查询,而我正在苦苦挣扎。有时需要超过 12 秒才能完成!

我有一个 SQL 小提琴 here,但是那里还没有数据。我认为数据量是导致缓慢的部分原因(wed_supplies + 邮政编码为 20k,cmets 为 60k),以及num_reviews 和avg_rating 子查询。

取出子查询将其缩短到大约 2 秒,但我需要它们提供的值,而且还需要更快。

SELECT *, c_title AS category,

        (SELECT COUNT(*) FROM comments WHERE site_id = '96' AND ec_type = 'review' AND ec_link_id = ws_id) AS num_reviews,
        (SELECT AVG(ec_rating) FROM comments WHERE site_id = '96' AND ec_type = 'review' AND ec_link_id = ws_id) AS avg_rating,
        (((acos(sin(( 52.1528253 *pi()/180)) * sin((`p_lat`*pi()/180))
            +cos(( 52.1528253 *pi()/180)) * cos((`p_lat`*pi()/180))
            * cos((( -0.6800496 - `p_lng`)*pi()/180))))*180/pi())*60*1.1515)
            AS distance
        FROM wed_suppliers 
            LEFT JOIN postcodes ON p_postcode = REPLACE(ws_postcode, ' ', '')
            LEFT JOIN c_content ON ws_category = c_id
        WHERE wed_suppliers.site_id = '96' AND c_content.site_id = '96'
        AND ws_hide = '0'
        AND ws_permalink != ''
        AND p_lat != '' AND p_lng != '' AND p_invalid = '0'
        HAVING distance <= 10

        ORDER BY distance ASC
        LIMIT 0,20

解释

id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra
1   PRIMARY     wed_suppliers   range   ws_permalink,site_id,ws_category,ws_hide    site_id     4   NULL    22628   Using where; Using temporary; Using filesort
1   PRIMARY     postcodes   eq_ref  PRIMARY,p_invalid,p_lng,p_lat   PRIMARY     12  func    1   Using where
1   PRIMARY     c_content   eq_ref  PRIMARY,site_id     PRIMARY     4   engine_4.wed_suppliers.ws_category  1   Using where
3   DEPENDENT SUBQUERY  comments    index_merge     site_id,ec_link_id,ec_type  site_id,ec_type     4,34    NULL    1   Using intersect(site_id,ec_type); Using where
2   DEPENDENT SUBQUERY  comments    index_merge     site_id,ec_link_id,ec_type  site_id,ec_type     4,34    NULL    1   Using intersect(site_id,ec_type); Using where

我已经使用了 EXPLAIN 返回的this glossary,但运气不佳。

如何优化此查询,使其以更合理的速度运行?以及如何将 EXPLAIN 翻译成更有用的内容。

【问题讨论】:

  • 如果您可以修改数据库架构,您可以查看您的索引
  • @heringer 索引位于我在顶部发布的 sqlfiddle 链接中
  • @Horse - 无论如何,桌子都不大。您可以尝试 1. 在运行查询之前清理数据从而避免连接中的 REPLACE 功能吗? 2. 为子查询创建临时表,然后加入主查询?

标签: mysql optimization explain


【解决方案1】:

看起来您的联接正在使用索引。剩下的子查询:

    (SELECT COUNT(*) FROM comments WHERE site_id = '96' AND ec_type = 'review' AND ec_link_id = ws_id) AS num_reviews,
    (SELECT AVG(ec_rating) FROM comments WHERE site_id = '96' AND ec_type = 'review' AND ec_link_id = ws_id) AS avg_rating,

我会推荐以下复合索引:comments(ec_link_id, ec_type, site_id)。这应该会加快子查询的速度。

【讨论】:

  • 我添加了以下内容,但执行时间几乎没有区别 - ALTER TABLE comments ADD INDEX comments_comp (ec_link_id, ec_type, site_id)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-18
  • 2013-03-01
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多