MySQL 在将数据保留在新结构中的同时转换表模式(你见过的最好的模式)

MySQL converting a tables schema while keeping the data in the new structure (best schema u ever see)

我正在分叉一个项目,想将 table 的模式之一转换为更..可行的结构

目前:

steamid | mapname | cp1 | cp2 | cp3 | cp4 | cp5 | cp6 | cp7 | cp8 | cp9 | cp10 | cp 11 | cp12 | cp13 | cp14 | cp15 | cp16 | cp17 | cp18 | cp19 | cp20 | cp21  | cp22 | cp23 | cp24 | cp25 | cp26 | cp27 | cp28 | cp29 | cp30 | cp31 | cp32 | cp33 | cp34 | cp35 | zonegroup

steamid 是用户 id,mapname 是地图,cp# 列存储特定检查点的玩家时间,zonegroup 存储地图"stage"

我想改成:

steamid | mapname | cp | time | zonegroup

是否有任何现实的解决方案来转换此 table 同时还保留数据,因此将先前存储在 cp1 中的时间移动到值为 1 的新 cp 列,并且新的time 列将包含旧 cp1 列中的任何内容

谢谢!

你可以使用(很多)union all

    select steamid, mapname, cp1 as cp , now(), zonegroup 
    from my_table  
    where cp1 is not null
    union all
    select steamid, mapname, cp2 , now(), zonegroup 
    from my_table  
    where cp2 is not null
    union all
    select steamid, mapname, cp3 , now(), zonegroup 
    from my_table  
    where cp3 is not null
    .....
    .....
    .....
    select steamid, mapname, cp34 , now(), zonegroup 
    from my_table  
    where cp34 is not null
    select steamid, mapname, cp35 , now(), zonegroup 
    from my_table  
    where cp35 is not null

您可以使用冗长的 INSERT ... SELECT 查询将数据传输到新的 table:

INSERT INTO new_table (steamid, mapname, cp, time, zonegroup)
SELECT * FROM (
    SELECT steamid, mapname, 1 AS cp, cp1 AS time, zonegroup FROM old_table
    UNION ALL
    SELECT steamid, mapname, 2, cp2, zonegroup FROM old_table
    UNION ALL
    ...
    SELECT steamid, mapname, 35, cp35, zonegroup FROM old_table) v