Search code examples
sqlforeign-keysprimary-keyanomaly-detection

Error: foreign key referring to primary keys from two different tables


I have created a test scenario like this:

I have three tables namely father, child, food.

Father table has primary auto increment key and a name column. Child table has primary auto increment key and a name column. Food has a column in which I want a foreign key and a column for food name.

father
-----------
id    name
1     kevin
2     adam

child
-----------
id    father_id    name
1     1            fred
2     1            john
3     2            alan

food
------------
person_id                name
1(from father table)     pizza
2(from child table)      burger
1(from child table)      hotdog

Now the food table has anomaly. I can't distinguish that (1 pizza) is for father or child...

Test Cases: select food.name from food where father.id = 1; OUTPUT: pizza select food.name from food where child.id = 1; OUTPUT: hotdog


Solution

  • I believe that design is pretty bad. Why don't you create a "person" table, populate it and determine if a person is a child or father in it, then use person id in food table?