Quantcast
Channel: MySQL Forums - InnoDB
Viewing all articles
Browse latest Browse all 1957

Foreign-Key not working (3 replies)

$
0
0
I'm having an issue with Foreign-Keys not enforcing business rules as I would expect. (Am hoping this is a silly SQL issue, and not a sign of a Data Modeling screw up on my end?!)

As always, I can't show everything, but hope this is enough to help you guys help me trouble-shoot!

This problem pertains to a Survey which has Questions that usually just have predefined Answer-sets (e.g. T/F, 1-5, 1-10, etc.) but may include "Value Lists" (e.g. Listing of Colors).


survey_question
Code:

id (PK)
stem (UK)
question_type

If the question-type is something like True-False, then there aren't any Answers below because it is predefined. However, if there is a non-standard list (e.g. Types of Ice Cream), then I add those choices in the survey_answer table and link them to the appropriate question in the survey_question table.

Follow me?


survey_answer
Code:

id (PK)
question_id (UK1)(FK)
choice (UK2)

(The composite unique index above ensures that you don't have "Red" listed several times for a given question!)


survey_multiple_response (Junction Table linked to lots of other tables not shown!)
Code:

id (PK)
article_id (UK1)(FK)
question_id (UK2)(FK)
answer_id (UK3)(FK)
member_id (UK4)(FK)


In my ERD, I show these links...
Code:

survey_question.id -||----0<- survey_answer.question_id

survey_answer.id -||----0<- survey_multiple_response.answer_id

survey_answer.question_id -||----0<- survey_multiple_response.question_id


I would expect the above table structure and FK contraints to prevent me from inserting an invalid Question-Answer pair, but that didn't happen?!


Here is my survey_answer table...
Code:

id question_id choice
--- ------------ -------
1 2 Work
2 2 Church
3 2 Other
4 6 Red
5 6 Green
6 6 Blue


And here is my survey_multiple_response table which contains a bogus record (i.e. ID=4) since "4" is not a value Answer-Choice for Question #2...
Code:

id article_id question_id answer_id member_id
--- ----------- ------------ ---------- ----------
1 1 2 1 13
2 1 2 2 13
3 1 2 3 13
4 1 2 4 13 <==== Invalid Question-Answer combination


Is there a way to fix this??

Sincerely,


Debbie

Viewing all articles
Browse latest Browse all 1957

Trending Articles