我正在嘗試使用 sql 變得更好,但是我對我的一項練習有一些問題/疑問。所以我想到了下面這種情況。我有三張桌子:
STUDENT
---- ------- ----------
| ID | NAME | LEVEL |
---- ------- ----------
| 1 | Tom | beginner |
| 2 | Peter | expert |
| 3 | Kate | beginner |
| 4 | John | beginner |
---- ------- ----------
COURSE
---- -----------
| ID | NAME |
---- -----------
| 1 | Math |
| 2 | English |
| 3 | French |
| 4 | Chemistry |
---- -----------
STUDENT_COURSE
------------ -----------
| STUDENT_ID | COURSE_ID |
------------ -----------
| 1 | 1 |
| 1 | 2 |
| 3 | 1 |
| 4 | 3 |
------------ -----------
但一段時間后,我要求將課程劃分為更具體的名稱。
Math -> Math_Beginner, Math_Expert
English -> English_Beginner, English_Expert
French -> French_Beginner, French_Expert
Chemistry -> Chemistry_Beginner, Chemistry_Expert
所以在COURSE表中看起來像那樣
---- --------------------
| ID | NAME |
---- --------------------
| 1 | Math_Beginner |
| 2 | English_Beginner |
| 3 | French_Beginner |
| 4 | Chemistry_Beginner |
| 5 | Math_Expert |
| 6 | English_Expert |
| 7 | French_Expert |
| 8 | Chemistry_Expert |
---- --------------------
并且知道當我被卡住時我是正確的。因為我也需要更新STUDENT_COURSE。顯然,我可以使用硬編碼的值來完成,但如果表格中有成千上萬個條目,則需要很長時間。所以我在考慮更通用的方法。學生確實包含存盤在哪里LEVEL的列,并且與課程名稱的后綴對應。所以我想用它。
UPDATE student_course SET course_id = (here I would need to have current value of COURSE.NAME and STUDENT.LEVEL, and if it was Math and level is beginner I would put Math_Beginner)
任何想法我怎么能做這種遷移(我想稱之為遷移太多了)
uj5u.com熱心網友回復:
我假設表之間存在父子關系,所以首先你需要備份你的 course 和 student_course 表。
create table student_course_bck select * from student_course;
create table course_bck as select * from course
然后你可以分別截斷 student_course 和 course 表。
truncate table student_course;
truncate table course;
使用交叉產品創建每一個可能的課程。
insert into course select rownum, de from (select distinct(c.namex||'_'||initcap(s.levelx)) de from student s cross join course_bck c order by 1);
最后你可以更新你的 student_course 表。
insert into student_course (select * from (with levelx_tab as(select s.idx studentid, s.namex studentname, s.levelx studentlevel, c.idx courseid, c.namex coursename, c.namex||'_'||initcap(s.levelx) newcoursename from student s join student_course_bck sc
on s.idx = sc.STUDENT_ID
join course_bck c
on c.idx = sc.COURSE_ID) select t.studentid, cs.idx from levelx_tab t join course cs
on t.newcoursename = cs.namex));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/441431.html
