【问题标题】:Why is my MySQL query so slow?为什么我的 MySQL 查询这么慢?
【发布时间】:2011-03-07 07:37:10
【问题描述】:
Background:
entities tables currently has 14,111 records
articles table currently has 5211 records

我正在尝试查找所有处于活动状态(已完成)且具有实体“google”的文章

# Finding articles that have the entity google takes:
# 4 ms
SELECT `Article`.`id` FROM `articles_entities` AS `ArticlesEntity`
LEFT JOIN `entities` AS `Entity` ON (`ArticlesEntity`.`entity_id` = `Entity`.`id`)
WHERE `Entity`.`strict` = 'google'

# Finding articles that have the entity google and is active takes:
# 1800 ms
SELECT `Article`.`id` FROM `articles_entities` AS `ArticlesEntity` 
LEFT JOIN `entities` AS `Entity` ON (`ArticlesEntity`.`entity_id` = `Entity`.`id`)
LEFT JOIN `articles` AS `Article` ON (`ArticlesEntity`.`article_id` = `Article`.`id`)
WHERE `Entity`.`strict` = 'google' AND `Article`.`state` = 'completed'

查询时间过长可能有什么问题?

我要补充一点,数据透视表中的两个字段都已编入索引。

提前感谢您的帮助

更新

id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE Entity ref PRIMARY,strict strict 767 const 1 Using where
1 SIMPLE ArticlesEntity ref article_id,entity_id,article_id_2 entity_id 108 b2b.Entity.id 4  
1 SIMPLE Article eq_ref PRIMARY,state PRIMARY 108 b2b.ArticlesEntity.article_id 1 Using where

【问题讨论】:

  • 查询返回多少行?

标签: php mysql query-optimization


【解决方案1】:

Entity.strict 或 Article.state 未编入索引。 在 SELECT 语句之前使用 EXPLAIN 并检查哪些表正在被完全扫描。这将暗示需要索引的内容。

【讨论】:

  • 你在每张表上有什么索引,EXPLAIN 告诉你什么?
【解决方案2】:

你真的需要左连接吗?!恕我直言,如果没有它,您的查询应该会得到提升;)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-26
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 2011-03-11
    • 2013-07-09
    • 2017-10-12
    • 1970-01-01
    相关资源
    最近更新 更多