P粉0463871332023-08-23 11:13:47
I have a slightly different way of accomplishing this than the accepted answer. This approach avoids using GROUP_CONCAT which has a 1024 character limit by default and won't work if you have a lot of fields unless you change the limit.
SET @sql = ''; SELECT @sql := CONCAT(@sql,if(@sql='','',', '),temp.output) FROM ( SELECT DISTINCT CONCAT( 'MAX(IF(pa.fieldname = ''', fieldname, ''', pa.fieldvalue, NULL)) AS ', fieldname ) as output FROM product_additional ) as temp; SET @sql = CONCAT('SELECT p.id , p.name , p.description, ', @sql, ' FROM product p LEFT JOIN product_additional AS pa ON p.id = pa.id GROUP BY p.id, p.name, p.description'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
P粉7680455222023-08-23 00:34:41
In MySQL, the only way to do this dynamically is to use prepared statements. Here is a good article about them:
Dynamic pivot table (convert rows to columns)
Your code will look like this:
SET @sql = NULL; SELECT GROUP_CONCAT(DISTINCT CONCAT( 'MAX(IF(pa.fieldname = ''', fieldname, ''', pa.fieldvalue, NULL)) AS ', fieldname ) ) INTO @sql FROM product_additional; SET @sql = CONCAT('SELECT p.id , p.name , p.description, ', @sql, ' FROM product p LEFT JOIN product_additional AS pa ON p.id = pa.id GROUP BY p.id, p.name, p.description'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
ViewDemo
Note: The character limit of the GROUP_CONCAT function is 1024 characters. See parameter group_concat_max_len