2016-01-01 26 views
2

我得到了3個表,叫做class,student和class_student(解析表)。這是由於班級和學生之間存在多種多樣的關係。一個學生可以有很多班,一個班可以有很多學生。類中的字段是(class_id,class_start_time和class_end_time),student(student_id,student_name,student_age),class_student(student_id,class_id)。我的問題是:在課堂上,它包括學生,我如何將學生添加到班級表中?或者我應該使用解析表?我對解析表的理解很薄弱,我不確定它的目的是什麼。解析表(mysql,php)

謝謝大家的回答!

當我向班級學生表中添加新記錄時,我是否也向班級表添加了新記錄?

+1

這是完全正常使用該類型的表得到的,' class_student'在你的例子中。當你需要多對多的關係時。你可以繼續。 – abeyaz

+0

''我如何將學生添加到班級表中?' - 嗯,你不這樣做。您可以使用它們之間的表格連接記錄,完全如您所述。有什麼問題? – David

+1

我認爲一個更常見的術語是_relation table_。 – Barmar

回答

0

解決多對多關係的最常見方法是通過單獨的relation table(正如Barmar指出的那樣)。

你的情況,該表可能有以下字段:

table class_students 
-------------------- 
id  // an unique id of that relationship; 
     // could be ommitted, could be an autoincrement, 
     // could also be a "handcrafted" id like classid_userid -> 21_13 (I need this kind of id's for an ember-api. 
     // All depending on your needs 
class // the id of the related class 
student // the id of the related student 
// maybe add additional fields: 
type  // to describe that relationship 
sort  

然後你會得到一個特定類的所有的學生都像這樣:

$class_id = 1; 
$sql = "Select * from students, class_students where students.id=class_students.student AND class_student.class=".$class_id; 
// note, that you should do that via prepared statements, 
// this is only for simplicity to show how to proceed. 
+0

插入語句怎麼樣?我只將學生插入class_student表嗎?上課表怎麼樣? – John

0

你不會增加學生班級表。如果你這樣做,在第一個階段沒有把學生與學生分開的觀點(你已經防止了數據冗餘)。我相信桌子的結構足以達到你的目標。作爲學生和班級表中主鍵的輔助鍵(student_id,class_id)分別執行作業。

類表

id| title | start | end 
1 Biology 8am 10am 
2 English 10am 12pm 

學生表

id | name | 
1 John 
2 Doe 

從表student_class表

student_id | class_id 
1    1 
1    2 
2    1 

,我可以

  1. 獲取所有課程約翰(user.id:1)註冊

    SELECT FROM student_class WHERE student.student_id = '1' 
    
  2. 所有已註冊的生物學學生(class.id:1)

    SELECT FROM student_class WHERE student.class_id = '1' 
    

    注意我知道你在結果中需要這裏的學生的名字。 很簡單,只是「LEFT JOIN」與student_class表類表上student_class.class_id = student.id

然後爲每個從student_class表中獲取的記錄中,「名稱」(或其他您選擇列包含在結果集中)將從類表中添加。

注意你剛剛加入class表的方式,你可以做同樣的student表。例如,你想學生打印自己的時間表進行歸類他們註冊了,你仍然會從student_class表中選擇和startend一次使用LEFT JOIN

+0

插入語句怎麼樣?當我向class_student表中添加一條新記錄時,我還需要爲類添加一條新記錄。我怎麼做? – John