简体   繁体   English

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

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

I need to split my MySQL table rows into multiple rows based on the number of students applying for the course with certain course code. 我需要根据申请具有特定课程代码的课程的学生人数,将MySQL表行拆分为多行。

在此处输入图片说明

basically, I need to separate the poorly designed MySQL table into rows so each student ends up in its designated row generated with the relevant course_code and unique id (id_new). 基本上,我需要将设计不良的MySQL表分成几行,以便每个学生最终进入由指定的行生成,该行由相关的course_code和唯一的id(id_new)生成。 Notice that the total number of studens in course1_students and course2_students will obviously be equal to the number of rows in the needed table. 请注意,course1_students和course2_students中的学生总数显然将等于所需表中的行数。

Appreciate any help! 感谢任何帮助!

To split each row into two rows, get two copies of each row in the FROM via cross join of the poorly designed table with a two-row constant table. 要将每一行分成两行,请通过设计不良的表与两行常量表的交叉联接,在FROM中获得每一行的两个副本。 To get courseX_student rows for each row of that table in the FROM, cross join with a table of integers >= 0 on course_students. 要在FROM中获取该表的每一行的courseX_student行,请对Course_students上的整数表> = 0进行交叉连接。 Insert the following rows into a table with auto_incremented id_new. 将以下各行插入具有auto_incremented id_new的表中。 (I'll assume that a courseX_students value of 0 produces no output rows. Because you haven't given the exact meaning of the tables.) (我假设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 is redundant (and name probably belongs in a separate table) id_new是多余的(名称可能属于一个单独的表)

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

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