我有一张这样的产品零件表:

零件

part_id      part_type      product_id
--------------------------------------
1            A              1
2            B              1
3            A              2
4            B              2
5            A              3
6            B              3

我想要一个查询,将返回这样的表:
product_id      part_A_id      part_B_id
----------------------------------------
1               1              2
2               3              4
3               5              6

在其实际实现中,将有数百万个产品零件

最佳答案

不幸的是,MySQL没有PIVOT函数,但是您可以使用聚合函数和CASE语句对其进行建模。对于动态版本,您将需要使用准备好的语句:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(case when part_type = ''',
      part_type,
      ''' then part_id end) AS part_',
      part_type, '_id'
    )
  ) INTO @sql
FROM
  parts;
SET @sql = CONCAT('SELECT product_id, ', @sql, '
                  FROM parts
                   GROUP BY product_id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

参见SQL Fiddle With Demo

如果只有几列,则可以使用静态版本:
select product_id,
  max(case when part_type ='A' then part_id end) as Part_A_Id,
  max(case when part_type ='B' then part_id end) as Part_B_Id
from parts
group by product_id

关于MySQL动态枢轴,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12630128/

10-16 16:20