行表的行转换为头表的列

行表的行转换为头表的列_第1张图片

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(CASE WHEN d.type = ''',
      type,
      ''' THEN d.value END) AS ',
      type
    )
  ) INTO @sql
FROM details;

SET @sql = CONCAT('SELECT 
                    h.id, 
                    h.name, ', @sql, ' 
                  FROM headers h
                  LEFT JOIN details d ON d.header_id = h.id
                   GROUP BY h.id, h.name');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

你可能感兴趣的:(数据库,sql,mysql)