MySQL pivot table query with dynamic columns

后端 未结 3 1576
一个人的身影
一个人的身影 2020-11-21 22:12

I\'m using the following tables for storing product data:

mysql> SELECT * FROM product;
+---------------+---------------+--------+
| id | name     | descr         


        
3条回答
  •  独厮守ぢ
    2020-11-21 23:02

    I have a slightly different way of doing this than the accepted answer. This way you can avoid using GROUP_CONCAT which has a limit of 1024 characters and will not work if you have a lot of fields.

    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');
    
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    

提交回复
热议问题