Skip to content

Instantly share code, notes, and snippets.

@AlexeySetevoi
Last active April 17, 2017 14:02
Show Gist options
  • Save AlexeySetevoi/c34ad16cd34278a58354b49da9d5906b to your computer and use it in GitHub Desktop.
Save AlexeySetevoi/c34ad16cd34278a58354b49da9d5906b to your computer and use it in GitHub Desktop.
mysql pivot attr reverse(also now as pivot-table) as view
SET @sql = NULL;
SET @sourcetable = 'Table';
set @viewname = CONCAT(@sourcetable,'F');
SET @@group_concat_max_len = 10000;
SELECT GROUP_CONCAT(DISTINCT
CONCAT(
'MAX(IF(name = ''',
name,
''', data, NULL)) AS ',
'''',
name,
''''
)
)
INTO @sql
FROM Table
WHERE 'name' IS NOT NULL AND 'name' != '';
SET @sql = CONCAT('CREATE OR REPLACE VIEW ', @viewname, ' AS ','SELECT id,parent_id, ', @sql, ' FROM `Table` GROUP BY parent_id');
SELECT @sql;
PREPARE attr_varchar FROM @sql;
EXECUTE attr_varchar;
DEALLOCATE PREPARE attr_varchar;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment