如何用普通的父母表保持参照完整性?

时间:2009-10-16 12:32:37

标签: sql database database-design referential-integrity

假设我有一个包含“问题小组”的表格

GroupID | value
--------+------
42      | How often do you
9071    | Other question
...

而且,对于每组问题,我都有“问题”和“可能的答案”

Group | QuestionID | value
------+------------+------
42    | 5          | ... brush your teeth?
42    | 89         | ... go to the movies?
9071  | 709        | ... another question ...
...
Group | Answer | value
------+--------+------
42    | 134    | several times per day
42    | 135    | twice a day
42    | 71     | once a day
42    | 803    | every other day
42    | 8      | once a week
42    | 666    | once a month
...

现在,在PHP / HTML中,我做了一个问题的完整交叉产品和第42组的可能答案,以构建一个2条目表,用户将选择他/她的答案(HTML version

How often do you      | N/d | 2/d | 1/d | d*2 | 1/w | 1/m |
----------------------+-----+-----+-----+-----+-----+-----+
... brush your teeth? | ( ) | (X) | ( ) | ( ) | ( ) | ( ) |
... go to the movies? | ( ) | ( ) | ( ) | ( ) | (X) | ( ) |

我知道我需要 牙齿insert into answers (question, answer, ...) values (5, 135, ...)
电影insert into answers (question, answer, ...) values (89, 8, ...)

问题是:有没有办法强制执行answers表中的问题和回答“属于”同一组问题?

我想要那个 insert into answers (question, answer, ...) values (709, 71, ...)
被禁止,因为问题709“属于”9071组,答案71属于第42组。

2 个答案:

答案 0 :(得分:1)

嗯,答案与问题有关,而不是与群组有关(至少不是直接),所以我认为“可能的答案”表应该是:

Question | Answer | value
---------+--------+------
5        | 134    | several times per day

然后当你插入答案时,你会给出QuestionId和AnswerId,他们一起引用“可能的答案”,从而间接引用该组。

答案 1 :(得分:0)

您添加了GroupQuestionIDAnswer列,然后创建了两个外键,一个在(Group, QuestionID)上,另一个在(Group, Answer)上。