Userei semplicemente GROUP_CONCAT()
invece dei cursori per generare l'istruzione preparata:
SELECT CONCAT(
' SELECT MDE_ID,'
, GROUP_CONCAT(
't', MDF_ID, '.MFV_Value AS `', REPLACE(MDF_Label, '`', '``'), '`'
)
,' FROM ModuleEntries '
, GROUP_CONCAT(
'LEFT JOIN ModuleEntryFieldValues AS t', MDF_ID, '
ON t', MDF_ID, '.MFV_MDE_ID = ModuleEntries.MDE_ID
AND t', MDF_ID, '.MFV_MDF_ID = ', MDF_ID
SEPARATOR ' ')
) INTO @qry FROM ModuleFields;
Salva per la modifica degli spazi bianchi per renderlo più leggibile, con i tuoi dati di esempio @qry
conterrebbe quindi:
SELECT MDE_ID,
t1.MFV_Value AS `Height`,
t2.MFV_Value AS `Width`,
t3.MFV_Value AS `Weight`
FROM ModuleEntries
LEFT JOIN ModuleEntryFieldValues AS t1
ON t1.MFV_MDE_ID = ModuleEntries.MDE_ID AND t1.MFV_MDF_ID = 1
LEFT JOIN ModuleEntryFieldValues AS t2
ON t2.MFV_MDE_ID = ModuleEntries.MDE_ID AND t2.MFV_MDF_ID = 2
LEFT JOIN ModuleEntryFieldValues AS t3
ON t3.MFV_MDE_ID = ModuleEntries.MDE_ID AND t3.MFV_MDF_ID = 3
Si può quindi preparare ed eseguire tale istruzione:
PREPARE stmt FROM @qry;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @qry = NULL;
Che produce i seguenti risultati:
MDE_ID Height Width Weight 1 120cms 30cms (null)
Guardalo su sqlfiddle .