0

I have some complex constraints required and some span over multiple tables. Is it better to duplicate the column (part of the primary key) to enforce the constraint OR use a stored procedure instead?

Here is an example:

create table responses
(
   resp_id int PRIMARY KEY
   participant_id int,
   session_id int,
   form_id int,
   section_id int,
   sec_target_id int,
   quest_id int,
   input_method_id int,
   foreign key(form_id, section_id) references form_sections(form_id, section_id),
   foreign key(section_id, quest_id) references questions(section_id, quest_id),
   foreign key(session_id, form_id) references session_forms(session_id, form_id),
   unique(resp_id, session_id)
);

create table user_responses
(
   resp_id int PRIMARY KEY
   participant_id int,
   session_id int,
   instructor_id int,
   foreign key(resp_id, session_id) references responses(resp_id, session_id),
   foreign key(session_id, instructor_id) references session_instructors(session_id, instructor_id)
);

There can be two types of responses: anonymous or user. User responses has an instructor associated with it for each session. In the table user_responses, I duplicate the column session_id from responses table so I can enforce the constraint that the instructor_id is actually assigned to the selected session.

There are many complex constraints like this and some future additional requirements that may cause a DDL change, is it better to enforce the constraints through a SP or the method above?

4

1 回答 1

0

是的,通常最好复制列以在需要的地方强制执行约束。注意一些可能会在未来发生变化的极端情况,但总的来说,我认为这种方法没有任何问题。这里重要的一点是,能够强制执行复合外键很有帮助。我不记得 MySQL 是否具有此功能,但大多数 RDBMS 应该。

于 2012-09-04T04:41:05.263 回答