根据表中的值将MySQL行拆分为多行

时间:2014-12-19 15:38:50

标签: mysql join split rows

我需要根据申请该课程的学生人数将我的MySQL表行拆分成多行。

enter image description here

基本上,我需要将设计糟糕的MySQL表分成行,这样每个学生最终都会在其指定的行中生成相关的course_code和唯一的id(id_new)。请注意,course1_students和course2_students中的学生总数显然等于所需表中的行数。

感谢任何帮助!

2 个答案:

答案 0 :(得分:0)

要将每一行拆分为两行,请通过设计不良的表与两行常量表的交叉连接获取FROM中每行的两个副本。要在FROM中为该表的每一行获取courseX_student行,请在course_students上使用table of integers >= 0进行交叉连接。将以下行插入到具有auto_incremented id_new的表中。 (我假设courseX_students值为0不产生输出行。因为你没有给出表格的确切含义。)

select id,name,1 as course_students,
    case which
    when 1 then course1_code
    when 2 then course2_code
    end as course_code
from numbers
cross join (select 1 as which union select 2) w
cross join poorly
where n <
    case which
    when 1 then course1_students
    when 2 then course2_students
    end

答案 1 :(得分:0)

CREATE TABLE my_new_table AS
SELECT id
     , name
     , course1_students course_students
     , course1_code course_code 
  FROM my_table
 UNION
SELECT id
     , name
     , course2_students
     , course2_code 
  FROM my_table;

 ALTER TABLE my_new_table ADD PRIMARY KEY(id,course_code);

id_new是多余的(名称可能属于单独的表)