我在MySQL中使用派生表时遇到问题。使用派生表本身是否会减慢查询的处理速度?
这是我试图运行的查询。它不会执行,只会超时。
确实成功了。真的,我已将问题隔离到最后一次加入。当我取出最后一次加入时它工作正常。但是当我添加最后一个连接时,它拒绝执行。
SELECT cr.COMMUNICATIONS_ID AS ANSWER_ID,
cr.CONSUMER_ID as VIEWER_ID,
cr.ACTION_LOG_ID,
nc.PARENT_COMMUNICATIONS_ID AS QUESTION_ID,
nc.SENDER_CONSUMER_ID AS REPLIER_ID,
ces.EXPERT_SCORE AS REPLIER_EXPERTISE,
cim.CONSUMER_INTEREST_EXPERT_ID AS DOMAIN
FROM (SELECT 234 AS CONSUMER_ID,
ACTION_LOG_ID,
COMMUNICATIONS_ID
FROM consumer_action_log
WHERE COMM_TYPE_ID=4) AS cr
JOIN network_communications AS nc ON
cr.COMMUNICATIONS_ID=nc.COMMUNICATIONS_ID
JOIN communication_interest_mapping AS cim ON
nc.PARENT_COMMUNICATIONS_ID=cim.COMMUNICATION_ID
JOIN consumer_expert_score AS ces ON
nc.SENDER_CONSUMER_ID=ces.CONSUMER_ID
AND cim.CONSUMER_INTEREST_EXPERT_ID=ces.CONSUMER_EXPERT_ID;
答案 0 :(得分:2)
希望这有帮助...这里有一些mysql CREATE INDEX语句。基本上,如果您可以添加索引,请确保有一个索引覆盖连接两个或更多表的每个列。
CREATE INDEX idx_nc
ON network_communications(COMMUNICATIONS_ID);
CREATE INDEX idx_cim
ON communication_interest_mapping(COMMUNICATION_ID);
CREATE INDEX idx_ces
ON consumer_expert_score(CONSUMER_ID, CONSUMER_EXPERT_ID);
派生表本身并不坏,但在这种情况下(见下文),您将从consumer_action_log中提取comm_type_id为4的所有记录。似乎没有连接回其他表。这可能是sql永远不会返回的原因。
SELECT cr.COMMUNICATIONS_ID,
cr.CONSUMER_ID,
cr.ACTION_LOG_ID,
nc.PARENT_COMMUNICATIONS_ID,
nc.SENDER_CONSUMER_ID,
ces.EXPERT_SCORE,
cim.CONSUMER_INTEREST_EXPERT_ID
FROM (SELECT 234 AS CONSUMER_ID,
ACTION_LOG_ID,
COMMUNICATIONS_ID
FROM consumer_action_log
WHERE COMM_TYPE_ID=4) AS cr
JOIN network_communications AS nc ON
cr.COMMUNICATIONS_ID=nc.COMMUNICATIONS_ID
JOIN communication_interest_mapping AS cim ON
nc.PARENT_COMMUNICATIONS_ID=cim.COMMUNICATION_ID
JOIN consumer_expert_score AS ces ON
nc.SENDER_CONSUMER_ID=ces.CONSUMER_ID
AND cim.CONSUMER_INTEREST_EXPERT_ID=ces.CONSUMER_EXPERT_ID;
答案 1 :(得分:1)
除了John在anser中指出的查找表中应该存在的索引之外,我还要确保你的consumer_action_log表中的COMM_TYPE_ID也有索引。
然后,在您的子句中添加一个关键字...当查询组织得很好而不依赖于查询引擎进行优化时,我总能看到很好的结果...... see another sample here
SELECT STRAIGHT_JOIN
cr.COMMUNICATIONS_ID AS ANSWER_ID,
cr.CONSUMER_ID as VIEWER_ID,
etc... rest of your query...
可能是优化器正在尝试查看其他表以确定要获取的内容。请参阅我提供的其他StackOverflow答案中的注释。