Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting a foreign key with multiple values

I was wondering, is there any possibility to create a table where i have a table which accepts a foreign key but may have multiple values for the same row.

For example:

Employee(id,name,skillid);
Skill(Skillid,skillname);

here an instance for Employee could be

Employee(311,"john", (01,02) );
Skill (01,Java); Skill (02,C++);

I implemented the same making primary key for the table as (is,skillid)

But in a case i have a table :

create table Movie (Movie_ID varchar(5),                              
                            Cast varchar(5),
                            foreign key(Cast) references Person(Person_ID), 
                            primary key(movie_id, Cast));

and another table :

create table Awards  (Award_Id varchar(5),
                                Person_Id varchar(5), 
                                Movie_Id varchar(5),
                                Award_Name  varchar(30),
                                Year number(4),
                                Organization_Id varchar(5),
                                primary key (Award_id,year,Organization_Id),
                                foreign key(Person_Id) references Person(Person_ID),
--                                foreign key(Movie_ID) references Movie(Movie_ID),
                                foreign key(Organization_Id) references Organization(Organization_Id));

In this case i am not able to use Movie_ID as a Foreign key since the table it is referencing has combination of 2 things as its primary key. And i am not using 2nd of those attribute in the Awards table.

Any hints how this can be implemented ?

like image 500
typedef1 Avatar asked Feb 14 '12 21:02

typedef1


1 Answers

Unfortunately you've just asked the age old question;

How do I put two things in one column?

The answer is, of course, that you don't; you have two columns. To extend your employee example your employee table would become:

create table employees (
   id number
 , name varchar2(4000)
 , skill_1 number
 , skill_2 number
 , constraint employee_pk primary key (id)
 , constraint employee_skill_1_fs 
      foreign key ( skill_1 ) 
   references skills(skillid)
 , constraint employee_skill_2_fs 
      foreign key ( skill_2 ) 
   references skills(skillid) 
   );

As you can see this isn't a particularly pretty thing to do and breaks normalisation; what happens if you want your employee ( or your employee wants of course ) to have 3 skills? Or 10?.

It would probably be better to create a third table and do all your joins by a single primary and foreign key; so you would have

employees ( employee_id, ..., pk employee_id);
employee_skills ( employee_id, skill_id, ..., pk employee_id, skill_id, fk skill_id );
skills ( skill_id, description, ..., pk skill_id );
like image 144
Ben Avatar answered Sep 23 '22 16:09

Ben