开发者社区> 问答> 正文

MySQL透视表与动态列的查询

我正在使用下表存储产品数据:

mysql> SELECT * FROM product; +---------------+---------------+--------+ | id | name | description | stock | +---------------+---------------+--------+ | 1 | product1 | first product | 5 | | 2 | product2 | second product| 5 | +---------------+---------------+--------+

mysql> SELECT * FROM product_additional; +-----------------+------------+ | id | fieldname | fieldvalue | +-----------------+------------+ | 1 | size | S | | 1 | height | 103 | | 2 | size | L | | 2 | height | 13 | | 2 | color | black | +-----------------+------------+ 使用以下查询从两个表中选择记录

mysql> SELECT p.id , p.name , p.description ,MAX(IF(pa.fieldname = 'size', pa.fieldvalue, NULL)) as size ,MAX(IF(pa.fieldname = 'height', pa.fieldvalue, NULL)) as height ,MAX(IF(pa.fieldname = 'color', pa.fieldvalue, NULL)) as color FROM product p LEFT JOIN product_additional AS pa ON p.id = pa.id GROUP BY p.id +---------------+---------------+--------+---------+--------+ | id | name | description | size | height | color | +---------------+---------------+--------+---------+--------+ | 1 | product1 | first product | S | 103 | null | | 2 | product2 | second product| L | 13 | black | +---------------+---------------+--------+---------+--------+ 一切都正常工作:)

因为我动态地填充了“附加”表,所以如果查询也是动态的,那就很好了。这样,我不必每次输入新的字段名和字段值就更改查询。

展开
收起
保持可爱mmm 2020-05-10 17:12:35 488 0
1 条回答
写回答
取消 提交回答
  • MySQL中动态执行此操作的唯一方法是使用Prepared语句。这是一篇关于它们的好文章:

    动态数据透视表(将行转换为列)

    您的代码如下所示:

    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; 观看演示

    注意:GROUP_CONCAT函数的限制为1024个字符。参见参数group_concat_max_lenMySQL中动态执行此操作的唯一方法是使用Prepared语句。这是一篇关于它们的好文章:

    动态数据透视表(将行转换为列)

    您的代码如下所示:

    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; 观看演示

    注意:GROUP_CONCAT函数的限制为1024个字符。参见参数group_concat_max_len来源:stack overflow

    2020-05-10 17:12:54
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
One Box: 解读事务与分析一体化数据库 HybridDB for MySQL 立即下载
One Box:解读事务与分析一体化数据库HybridDB for MySQL 立即下载
如何支撑HTAP场景-HybridDB for MySQL系统架构和技术演进 立即下载

相关镜像