【问题标题】:Split MySQL row into multiple rows based on a value in the table根据表中的值将 MySQL 行拆分为多行
【发布时间】:2015-02-18 13:51:46
【问题描述】:

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

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

感谢任何帮助!

【问题讨论】:

  • 可能可以通过几个工会来做到这一点。不过可能还有比这更好的选择。
  • 谢谢。我尝试了 UNION 并最终得到了 12 行代码。我稍后会发布结果,但我希望有一种更快/更清洁的方法。
  • 向我们展示一下 UNION

标签: mysql join split rows


【解决方案1】:
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 是多余的(并且 name 可能属于单独的表)

【讨论】:

    【解决方案2】:

    要将每行拆分为两行,请通过将设计不佳的表与两行常量表的交叉连接获取 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
    

    【讨论】:

      猜你喜欢
      • 2020-02-10
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-10
      • 2023-04-01
      • 1970-01-01
      相关资源
      最近更新 更多