P粉6048485882023-08-28 16:02:00
My approach is slightly different from the accepted answer. This way you avoid using GROUP_CONCAT, which has a default limit of 1024 characters, which 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粉4959559862023-08-28 10:33:43
The only way to do this dynamically in MySQL is to use prepared statements. Here is a good article about them:
Dynamic PivotTable (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;
SeeDemo
Note: The length of the GROUP_CONCAT function is limited to 1024 characters. View parameter group_concat_max_len