joined table rows into columns with column titles from original rows

守給你的承諾、 提交于 2019-12-06 12:13:23

I'd just use GROUP_CONCAT() instead of cursors to generate the prepared statement:

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;

Save for whitespace editing to make it more readable, with your sample data @qry would then contain:

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

One can then prepare and execute that statement:

PREPARE stmt FROM @qry;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @qry = NULL;

Which yields the following results:

MDE_ID    Height    Width    Weight
     1    120cms    30cms    (null)

See it on sqlfiddle.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!