繁体   English   中英

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

[英]Split MySQL row into multiple rows based on a value in the table

我需要根据申请具有特定课程代码的课程的学生人数,将MySQL表行拆分为多行。

在此处输入图片说明

基本上,我需要将设计不良的MySQL表分成几行,以便每个学生最终进入由指定的行生成,该行由相关的course_code和唯一的id(id_new)生成。 请注意,course1_students和course2_students中的学生总数显然将等于所需表中的行数。

感谢任何帮助!

要将每一行分成两行,请通过设计不良的表与两行常量表的交叉联接,在FROM中获得每一行的两个副本。 要在FROM中获取该表的每一行的courseX_student行,请对Course_students上的整数表> = 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
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是多余的(名称可能属于一个单独的表)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM