Link to home
Start Free TrialLog in
Avatar of Jsara
Jsara

asked on

can there be two foriegn keys in a table - both the foriegn keys reference a primary key in other table

can there be two foriegn keys in a table - both the foriegn keys reference a primary key in other table. (The table is going to be built on MYSQL backend - connected to MS access front end)



I have a group of items that I need to mark different categories. Some items belong to both the categories.
Hence I am trying to build a table like
Example:
table name - Item-categories
Itemid, categoryid1, categoryid2
1           1                       2
2           2                  
3           1                      2

(Categroyid and categoryid2 are the foriegn keys and represent the catgegoryID in the category table).

If the above is not legitimate design, how to acheive the best.
Avatar of Jim Dettman (EE MVE)
Jim Dettman (EE MVE)
Flag of United States of America image

 
  While you can, it's not a great idea. You'll have all kinds of problems when it comes to queries against the tables.

  Instead, create another table, which for each Item will have one record for each category that the item belongs to.

Jim.
You shouldn't have columns that repeat the same data.  The proper way to have this (called a Many to many join) is with three tables

Table1 - ItemList
Itemid, ItemName, etc

Table 2 - Categories
CategoryID, CategoryName

Table3 - Join table
ItemID, CategoryID

Table 3 has a primary key of ItemID, CategoryID, and one entry for each pair
Avatar of Jsara
Jsara

ASKER

Definitely, sorry I was not clear.
What I wrote was to have a 3rd table.
I have items, categories and a 3rd table called item_categories.

So are you suggesting in table - it should be just 2 columns of itemid and categoryid only
and not 3 columns with Item id and 2 other category id columns.
<<So are you suggesting in table - it should be just 2 columns of itemid and categoryid only>>

 Exactly.  An item in multiple categories is represented with multiple records rather then multiple fields in a single record.

  This makes it simple to answer questions such as:

How many categories is an item in?
How many items have category xyz?

  If the data were in multiple fields, you'd have to visit each item record and look in every category field to answer questions such as those.

Jim.
ASKER CERTIFIED SOLUTION
Avatar of Jim Dettman (EE MVE)
Jim Dettman (EE MVE)
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
It is perfectly reasonable and correct for a table to have multiple foreign keys referencing another table.

In your specific case however I suggest you change the design along the lines that JDettman suggested. It appears to make more sense to allow any number of categories per item and not restrict yourself to two.