【发布时间】:2016-01-26 21:42:23
【问题描述】:
我的查询遇到了一些困难,其中包含多个左联接以及 group by 和 order。
文本表和 textdetails 包含 +- 800k 条记录
复制表和复制详细信息包含 +- 200k 条记录
其他表要小很多。
我对执行左连接的每一列都有外键。 我还在执行 where 语句的每一列上都有索引。 下面的 MySQL 查询仍然运行大约 40 秒。 排除 Group By 会有所改善。 省略 Order By 会改进很多。
我做了一些研究,但我仍然对如何改进我的查询或索引感到困惑。
SELECT * FROM `copy`
LEFT JOIN `domain` ON domain.domain_id = copy.copy_domain_id
LEFT JOIN `domaincategory` ON copy.copy_domain_id = domaincategory.domaincategory_domain_id AND domaincategory.domaincategory_account_id = copy.copy_account_id
LEFT JOIN `text` ON text.text_id = copy.copy_text_id LEFT JOIN `textdetails` ON textdetails.textdetails_text_id = text.text_id
LEFT JOIN `channel` ON channel.channel_domain_id = domain.domain_id AND channel.channel_account_id = copy.copy_account_id
LEFT JOIN `feed` ON feed.feed_id = text.text_feed_id
WHERE (feed.feed_account_id = 96) AND (feed.feed_flag_delete IS NULL) AND (text.text_flag_delete IS NULL) AND (copy.copy_flag_delete IS NULL) AND (copy.copy_tracking_date_found IS NOT NULL) AND (channel.channel_active = 1)
GROUP BY `copy`.`copy_id`
ORDER BY `copy`.`copy_tracking_date_found` DESC LIMIT 50
EXPLAIN 选项的结果如下所示,但我不知道如何正确阅读和使用它
ID : 1
Select_type : SIMPLE
Table : Feed
Type : Ref
Possible_Keys: PRIMARY,fk_feed_account_id,feed_flag_delete
Key: fk_feed_account_id
Key_len : 4:
Ref : const
Rows : 1
Extra: Using where; Using temporary; Using filesort
ID : 1
Select_type : SIMPLE
Table : text
Type : Ref
Possible_Keys: PRIMARY,fk_text_feed_id,text_flag_delete
Key: text_flag_delete
Key_len : 2
Ref : const
Rows : 2628
Extra: Using where
ID : 1
Select_type : SIMPLE
Table : textdetails
Type : Ref
Possible_Keys: fk_textdetails_text_id
Key: fk_textdetails_text_id
Key_len : 5
Ref : text.text_id
Rows : 1
Extra:
ID : 1
Select_type : SIMPLE
Table : copy
Type : Ref
Possible_Keys: fk_copy_account_id,fk_copy_domain_id,fk_copy_text_...
Key: fk_copy_text_id
Key_len : 4
Ref : text.text_id
Rows : 1
Extra: Using where
ID : 1
Select_type : SIMPLE
Table : domain
Type : eq_ref
Possible_Keys: PRIMARY
Key: PRIMARY
Key_len : 4
Ref : copy.copy_domain_id
Rows : 1
Extra: Using where
ID : 1
Select_type : SIMPLE
Table : domaincategory
Type : eq_ref
Possible_Keys: fk_domaincategory_account_id,fk_domaincategory_dom
Key: fk_domaincategory_domain_id
Key_len : 4
Ref : domain.domain_id
Rows : 1
Extra:
ID : 1
Select_type : SIMPLE
Table : channel
Type : ref
Possible_Keys: fk_channel_account_id,fk_channel_domain_id,channel...
Key: fk_channel_domain_id
Key_len : 4
Ref : copy.copy_domain_id
Rows : 2
Extra: Using where
也许我应该多解释一下这些关系?
提要:文本 = 1:n
文本 : textdetails = 1:1
文本:复制 = 1:n
复制:域 = n:1
频道:域 n:1
【问题讨论】:
-
你需要让 MySQL 解释查询在做什么:dev.mysql.com/doc/refman/5.5/en/execution-plan-information.html
-
你为什么不编辑你的问题并发布它们?
-
我刚做了。似乎无法弄清楚如何正确读取 EXPLAIN 函数
标签: mysql join group-by sql-order-by