iT邦幫忙

0

MySQL能否利用外鍵關聯表單的欄位建立索引

  • 分享至 

  • xImage

原本有四張表
student表,主鍵student_id和其他欄位
question表,主鍵question_id和其他欄位
answer表,主鍵answer_idquestion_id和其他欄位
student_qa表,student_idquestion_id複合主鍵和answer_id
由於answer和question是有對應關係的
所以理論上student_qa只需要紀錄student_idanswer_id即可,但是需要唯一索引的欄位卻是student_idquestion_id,目前是紀錄三個欄位設定索引,然後用程式確保answer_idquestion_id的對應是正確的
想要問的是
如果student_qaanswer_id欄位設為外鍵關連到answerstudent_qa是否能用自身的student_id欄位和answer表的question_id建立索引,這樣就可以避免自身紀錄的question_idanswer_id兜不起來的情況

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

2
海綿寶寶
iT邦大神 1 級 ‧ 2021-07-17 09:59:13
最佳解答

Table 的設計要以「需求」為出發點考量
就是「要查詢那些資訊」?例如:
1.學生問了那些問題
2.學生回答了那些問題
3.問題有那些答案

根據你的文字描述製圖如下
https://ithelp.ithome.com.tw/upload/images/20210717/200017874JaJm7Telp.png
坦白說我看不太懂,例如:
1.student_id 和 question_id 和 answer_id 的關係是什麼?
2.會不會問題還沒有答案的情形?
3.一個問題由一個學生發問;答案需要記錄是那個學生回答的嗎?

我稍微改了一下如下
https://ithelp.ithome.com.tw/upload/images/20210717/20001787erEevqz7lD.png

如果上圖可以滿足題意的所有需求
再來討論細節
不然就算我胡說八道
不用理我
/images/emoticon/emoticon25.gif

另外提供今天才發現的好物
就是免費免註冊線上畫 ERD的服務
下面是產生上面兩張圖的 source

//// -- LEVEL 1
//// -- Tables and References

// Creating tables
Table student as s {
  student_id int [pk] // auto-increment
}

Table question as q {
  question_id int [pk]
 }

Table answer as a {
  answer_id int [pk]
  question_id int
 }

Table student_qa as qa {
  student_id int [pk]
  question_id int [pk]
  answer_id int [pk]
 }

Ref: "student_qa"."answer_id" < "answer"."answer_id"
//// -- LEVEL 1
//// -- Tables and References

// Creating tables
Table student as s {
  student_id int [pk, increment] // auto-increment
}

Table question as q {
  question_id int [pk]
  student_id int 
 }

Table answer as a {
  answer_id int [pk]
  student_id int
 }

//// -- LEVEL 2

Table question_answer as qa {
  question_id int [pk]
  answer_id int [pk]
 }



// Creating references
// You can also define relaionship separately
// > many-to-one; < one-to-many; - one-to-one
Ref: s.student_id < q.student_id
Ref: s.student_id < a.student_id

Ref: qa.question_id - q.question_id
Ref: qa.answer_id - a.answer_id
迷路 iT邦新手 2 級 ‧ 2021-07-19 08:31:52 檢舉

question這張表是紀錄選擇題的問題
answer這張表是紀錄選擇題的選項,所以表中的question_id是關連到question的主鍵
student_qa這張表是紀錄學生選擇的答案
在原本的設計中question_id關連到question的主鍵,answer_id關連到answer的主鍵
由於學生不能重複回答相同問題,所以student_idquestion_id聯合組成student_qa的主鍵
但是如果student_qa.question_idstudent_qa.answer_id對應到的answer.question_id不相等的話,就會出現錯誤,原本是靠著程式碼避免這樣的問題
現在想問的是,能否將student_qaquestion_id省去後,將answer_id設定為外鍵關連到awser的主鍵,在利用這層關係將answer.question_id欄位抓過來student_qa當複合主鍵的欄位之一

我覺得答案是「不行」
看看別的高手有沒有辦法

迷路 iT邦新手 2 級 ‧ 2021-07-22 13:52:12 檢舉

想到另一個方式
answerquestion_idanswer_id建立unique索引
student_qa維持三個欄位不變,將question_idanswer_id設為複合外鍵,關連到answer的對應欄位
這樣一來,如果answer中不存在question_idanswer_id的組合資料,student_qa就無法新增,應該可以保證資料的正確性

我要發表回答

立即登入回答