如何执行MySQL查询来格式化和移动数据?

时间:2012-12-11 05:17:13

标签: mysql select group-by

我目前有一个34,930,054行MySQL数据库,其格式为条目(以前的编码器工作)在3列表中的多行中,即:

Part number 1 | height | 5cm  
Part number 1 | length | 10cm  
Part number 1 | width  | 5cm   
Part number 2 | length | 1cm  
Part number 2 | height | 3cm  
Part number 2 | width  | 8cm

我想将数据合并到一个更清洁的2列表中,以便以后输出。即:

Part number 1 | height: 5cm  <br /> length: 10cm <br /> width: 5cm  
Part number 2 | height: 1cm  <br /> length: 3cm <br /> width: 8cm 

如何查找具有SAME部件号的所有行,以上述2列格式(第1列中的部件号以及从原始表中第2列和第3列到第2列的所有数据)将行插入新表中新表)?

2 个答案:

答案 0 :(得分:1)

试试这个:

INSERT INTO parts_new (partnum, description)
SELECT partNum, GROUP_CONCAT(CONCAT(measurement_type, ' : ', measurement_value) 
              ORDER BY FIELD(measurement_type, 'height', 'length', 'width')  
              SEPARATOR ' <br /> ') description
FROM parts_old
GROUP BY partNum

INSERT INTO parts_new (partnum, width, LENGTH, height)
SELECT partNum, SUM(width) width, SUM(LENGTH) LENGTH, SUM(height) height
FROM (SELECT partNum, IF(measurement_type='width', measurement_value, 0) width, 
        IF(measurement_type='height', measurement_value, 0) height, 
        IF(measurement_type='length', measurement_value, 0) LENGTH
FROM parts_old) AS A
GROUP BY partNum

检查链接MySQL INSERT INTO...SELECT

答案 1 :(得分:0)

由于我不知道你真正的表名和列名,我假装他们看起来像这样:

parts_old(db table)

partnum   measurement_type  measurement_value
-------   ----------------  -----------------
1         width             5
1         length            10
1         height            5
2         width             8
2         length            1
2         height            3

如果我理解你的问题,你最终会得到以下结论:

parts_new(db table)

partnum   width  length  height
-------   -----  ------  ------
1         5      10      5
2         8      1       3

使用正确的列类型构建新表后,可以使用以下SQL将数据从旧表迁移到新表:

insert into parts_new (partnum, width, length, height)
(
    select 
        h.partnum as partnum,
        w.measurement_value as width,
        l.measurement_value as length,
        h.measurement_value as height 
    from 
        parts_old as w
    inner join 
        parts_old as l on l.partnum = w.partnum
    inner join
        parts_old as h on h.partnum = w.partnum
    where 
        w.measurement_type = 'width'
        and
        l.measurement_type = 'length'
        and
        h.measurement_type = 'height'    
    group by 
        h.partnum
)

我使用Sequel Pro在MySQL 5.1上进行了测试,以确保它有效。