Conceptually, I am trying to grab 8 separate survey scores for every user in my system. I want to output all 8 scores connected to a given user outputted on the same row. Here is my best shot to achieve this:
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
This returns the proper output, but however is terribly slow. How would you suggest I optimize it?
The first thing you need is an index on survey_scores(SET_ORDER, consumer_id, score) or at least survey_scores(SET_ORDER, consumer_id). It will then work quite well even with your query.
An alternative way to write it would be