MySQL pivot table query with dynamic columns

后端 未结 3 1582
一个人的身影
一个人的身影 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 22:58

    The only way in MySQL to do this dynamically is with Prepared statements. Here is a good article about them:

    Dynamic pivot tables (transform rows to columns)

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

    See Demo

    NOTE: GROUP_CONCAT function has a limit of 1024 characters. See parameter group_concat_max_len

提交回复
热议问题