gpt4 book ai didi

MySQL 查询优化消除不必要的连接

转载 作者:行者123 更新时间:2023-11-29 06:18:20 25 4
gpt4 key购买 nike

从概念上讲,我试图为系统中的每个用户获取 8 个单独的调查分数。我想输出与同一行上输出的给定用户相关的所有 8 个分数。这是我实现这一目标的最佳方法:

SELECT cp.CONSUMER_ID,
bsr1.SCORE AS SET_1_SCORE,
bsr2.SCORE AS SET_2_SCORE,
bsr3.SCORE AS SET_3_SCORE,
bsr4.SCORE AS SET_4_SCORE,
bsr5.SCORE AS SET_5_SCORE,
bsr6.SCORE AS SET_6_SCORE,
bsr7.SCORE AS SET_7_SCORE,
bsr8.SCORE AS SET_8_SCORE
FROM
CONSUMER_PROFILE AS cp
LEFT JOIN survey_scores AS bsr1
ON bsr1.SET_ORDER=1
AND bsr1.CUSTOMER_ID=cp.CONSUMER_ID
LEFT JOIN survey_scores AS bsr2
ON bsr2.SET_ORDER=2
AND bsr2.CUSTOMER_ID=cp.CONSUMER_ID
LEFT JOIN survey_scores AS bsr3
ON bsr3.SET_ORDER=3
AND bsr3.CUSTOMER_ID=cp.CONSUMER_ID
LEFT JOIN survey_scores AS bsr4
ON bsr4.SET_ORDER=4
AND bsr4.CUSTOMER_ID=cp.CONSUMER_ID
LEFT JOIN survey_scores AS bsr5
ON bsr5.SET_ORDER=5
AND bsr5.CUSTOMER_ID=cp.CONSUMER_ID
LEFT JOIN survey_scores AS bsr6
ON bsr6.SET_ORDER=6
AND bsr6.CUSTOMER_ID=cp.CONSUMER_ID
LEFT JOIN survey_scores AS bsr7
ON bsr7.SET_ORDER=7
AND bsr7.CUSTOMER_ID=cp.CONSUMER_ID
LEFT JOIN survey_scores AS bsr8
ON bsr8.SET_ORDER=8
AND bsr8.CUSTOMER_ID=cp.CONSUMER_ID

这会返回正确的输出,但速度非常慢。您建议我如何优化它?

最佳答案

您需要的第一件事是survey_scores(SET_ORDER,consumer_id,score)或至少是survey_scores(SET_ORDER,consumer_id)的索引。即使对于您的查询,它也能很好地工作。

另一种编写方式是

SELECT cp.CONSUMER_ID,
MAX(CASE WHEN bsr1.SET_ORDER=1 THEN bsr1.SCORE END) AS SET_1_SCORE,
MAX(CASE WHEN bsr1.SET_ORDER=2 THEN bsr1.SCORE END) AS SET_2_SCORE,
MAX(CASE WHEN bsr1.SET_ORDER=3 THEN bsr1.SCORE END) AS SET_3_SCORE,
MAX(CASE WHEN bsr1.SET_ORDER=4 THEN bsr1.SCORE END) AS SET_4_SCORE,
MAX(CASE WHEN bsr1.SET_ORDER=5 THEN bsr1.SCORE END) AS SET_5_SCORE,
MAX(CASE WHEN bsr1.SET_ORDER=6 THEN bsr1.SCORE END) AS SET_6_SCORE,
MAX(CASE WHEN bsr1.SET_ORDER=7 THEN bsr1.SCORE END) AS SET_7_SCORE,
MAX(CASE WHEN bsr1.SET_ORDER=8 THEN bsr1.SCORE END) AS SET_8_SCORE
FROM CONSUMER_PROFILE AS cp
LEFT JOIN survey_scores AS bsr1
ON bsr1.SET_ORDER in (1,2,3,4,5,6,7,8)
AND bsr1.CUSTOMER_ID=cp.CONSUMER_ID
GROUP BY cp.CONSUMER_ID

关于MySQL 查询优化消除不必要的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5238656/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com