Foreign key as Primary key

淺唱寂寞╮ 提交于 2019-12-10 16:21:20

问题


I designed tables like this:

table1: students
---------------------
PK id
name
number
...
---------------------

table2: students_score
---------------------
PK FK student_id
math_score
english_score
...
---------------------

Question 1

If some students doesn't have scores at all, is it good table design?

Question 2

If it's good design, then how can I make FK as PK in MySQL? I can't find out how. Everytime I try to make a relation like above SQLYog says this error: Can't create table 'students.#sql-a31_2c8e' (errno: 150)

Thanks

Update

I found an answer of the question 2 from here. This was just a problem of type(int, signed int).


回答1:


I would suggest something more along these lines:

table1: students
---------------------
PK id
name
number
...
---------------------

table3: classes
---------------------
pk id
name

table2: students_score
---------------------
fk student_id
fk class_id
score
PK(student_id, class_id)



回答2:


Use UNIQUE and FOREIGN KEY instead. It will allow you to use the FOREIGN KEY with your students_score table, and maintain the student_id column as unique.




回答3:


If some students doesn't have scores at all, is it good table design?

No, if some students doesn't have scores, there won't be (or shouldn't be) records on the students_score table. It is not a good design though, and that's why you get errors.

Your design should be something similar to:

students
---------------------
PK id
name
number

students_score
---------------------
FK student_id
math_score
english_score
...

Consider creating an UNIQUE index for your student_id on the students_score table, but that will limit your number of records per student to one, which maybe is not what you want.



来源:https://stackoverflow.com/questions/6578015/foreign-key-as-primary-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!