Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a Join table (association table) have a primary key ? many to many relationship

Does a Join table (association table) have a primary key ? many to many relationship. I've seen some Join tables with a primary key and some without can someone please explain when you would have a primary key in a join table and why?

Thank you in advance;-)

like image 941
Imran Avatar asked Jun 22 '10 10:06

Imran


People also ask

Do join tables have primary keys?

A table must have exactly one primary key to qualify as relational, but that key can be composed of multiple columns. A foreign key, by contrast, is one or more fields or columns that corresponds to the primary key of another table. Foreign keys are what make it possible to join tables to each other.

Can a many-to-many relationship have a primary key?

In a many-to-many relationship, a row in table A can have many matching rows in table B, and vice versa. You create such a relationship by defining a third table that is called a junction table. The primary key of the junction table consists of the foreign keys from both table A and table B.

How do you join two tables with many-to-many relationships?

When you need to establish a many-to-many relationship between two or more tables, the simplest way is to use a Junction Table. A Junction table in a database, also referred to as a Bridge table or Associative Table, bridges the tables together by referencing the primary keys of each data table.

Which table in a schema join contains the primary key?

The OrderId is the primary key on the Order table.


1 Answers

In a pure 'join' or junction table all the fields will be part of the primary key. For example let's consider the following tables:

CREATE TABLE USERS
  (ID_USER NUMBER PRIMARY KEY,
   FIRST_NAME VARCHAR2(32),
   LAST_NAME VARCHAR2(32));

CREATE TABLE ATTRIBUTES
  (ID_ATTRIBUTE NUMBER PRIMARY KEY,
   ATTRIBUTE_NAME  VARCHAR2(64));

A junction table between these to allow many users to have many attributes would be

CREATE TABLE USER_ATTRIBUTES
  (ID_USER NUMBER REFERENCES USERS(ID_USER),
   ID_ATTRIBUTE NUMBER REFERENCES ATTRIBUTES(ID_ATTRIBUTE),
   PRIMARY KEY(ID_USER, ID_ATTRIBUTE));

Sometimes you'll find the need to add a non-primary column to a junction table but I find this is relatively rare.

Share and enjoy.

like image 121