Download as pdf or txt
Download as pdf or txt
You are on page 1of 23

Relationships between Tables

There are three types of table relationships you can have in Access (One-to-Many, Many-to-Many,
and One-to-one), however, the One-to-Many is the most useful for the beginner, so that is what we
will look at, here. A One-to-Many relationship is a relationship between two tables where a record
in one table can be used repeatedly as a value in another table.
Creating One-to-Many Relationships between tables
The two most common reasons you will likely come across for creating one-to-many relationships
between tables are as follows:

1. To provide a lookup list for a field of a table that will have values that are repeated over
and over again. Example: in the Book Orders example from the Welcome tab, you would
likely be ordering multiple books from the same vendors any number of times. Rather than
have the user type in the vendor's name each time, you could draw those values from a
separate table that only lists those values once. This would:
a. Save time and prevent errors likely to occur when users manually input the same
values over and over again.
b. Allow you to update or change one of those values and have it instantly update in all
of its instances on the related table.
2. To create a field in a table that can contain multiple items. To continue with a similar
example, if we were to keep track of video orders for a library, we might have a main table
that represents each order we make to a specific vendor, with the date ordered, date
received, vendor name, etc. Within that table, we might want to actually reference the titles
on each order. However, since there would likely be multiple titles on a number of orders,
we couldn’t adequately represent that with a single field per record. Instead, we would
want a separate list of titles that reference the order they were part of.

We’ll look at a simple way to do each of these:

1. Using a table to provide lookup values to a field in another table (NOTE: the first two steps
assume the table you want to draw values from does not already exist)
a. Go to the “Create” tab on the toolbar at the top of the Access window and select
“Table” from the row of choices that appears under the tab.
b. Go to Design View (use the "View" dropdown menu at the top left) and save the
table, naming it for the type of
items you want in your lookup list
(this would be “Vendors” in the
book example, above). Then add
an additional field (you’ll be
keeping
the ID
field) that
will
contain
your
lookup
values. Save the new table again, and then add the items you wish to be in your
original table’s lookup column in the datasheet view of the new table.
Go back to the Design View of your original table. Select “Lookup Wizard” as the
data type of the field for which you want a list created.

c. The Lookup Wizard dialog box will pop up. On the first screen, you will be asked to
choose whether you wish to have the lookup column look up the values in a table or
query or whether you want to
type those values in
yourself. Choose the first
option, then, click “Next.”
d. The Lookup Wizard will then
ask you what table or query
will provide your
values. Select the table you
just created and click “Next.”

e. You will then be asked what


fields to use for your lookup
values. Select the field you
added in the new table (the "Vendors" Short Text field in this example), by double-
clicking the field name. Click “Next.”

f. On this screen, you will be asked


to provide a sort order for the
items in your combo box. Select
the field you chose on the
previous screen from the first
drop-down menu and have them
sorted in ascending order (this is
the default). Click “Next.”

g. The next screen gives you the


option of setting the width of your
columns. Click and drag the right
edge of the sample column visible
to adjust columns to the width desired. Keep the “Hide key column” box
checked. Click “Next.”
h. The last screen gives you the option to change the label for your lookup column (this
will usually be unnecessary). This screen will also give you a check box asking you
whether or not to “Enforce Referential Integrity.” If you check this, Access will
prevent you from deleting anything on the “one” side of you relationship that is
included in any records on other tables. For this type of use, it’d probably useful to
check it, but not essential. Click
“Next” when done.
i. This will return you to Design
View. You can now save your
table and go back to Datasheet
View. The field you set up
lookup values for should now
have a combo box drawing
values from your second table.
2. Using a second table to provide a
subset of data to your first. (We’ll use
the video orders example from
earlier. The goal is to have multiple
titles per each order.)
a. We would need separate tables for orders and for titles. Here are examples of what
each might look like in Design View:

b. We would then need to find a common attribute to link them. Since each video
order has a unique ID value and each title record is going to be part of a specific
order, the best place to start is with the ID field in our Video Orders table.
c. In order to link the two tables by the Video Orders ID value, we need to have a field
that can reference that value directly on our second table. We can do this by adding
a new field to the “Titles” table called “Video Order ID.” Because the original
datatype is numerical, this needs to be as well. (NOTE: This will be considered a
“foreign key”, as it references the primary key of another table.)

d. We now need to
create the
relationship between
the two tables so that Access will recognize that they are connected. Save and close
both tables, select the “Database Tools” tab from the menu at the top of your
Access window, then select the “Relationships” icon from the ribbon below. You
should get a pop up box asking you to choose which tables to show. Add both the
“Video Orders” and “Titles” table. You’ll then get a window like this:

e. In order to set up the


relationship, click the
“ID” field from the
“Video Orders” table
and drag it to the
“Video Order ID” filed
in the “Titles”
Table. You will get a
dialog box that looks
like this:

f. Access will
automatically create a
one- to-many
relationship between
the two fields. It will also give you a check box asking you whether or not to
“Enforce Referential Integrity.” For something like the video order list, where one
list is entirely dependent on the other, you will want to check this. That way if you
attempt to delete or change something that is part of a relationship, Access will
warn you about it.

Once the relationship is established and saved, you can re-open the form on the “one” side of your
one-to-many relationship, and you will see there is a “+” sign next to each record:

Outlook has automatically created a sub-datasheet that can be expanded out to show the records in
your related table. Clicking on each plus sign will expand the sub-datasheet, and show you the
related records, and also allow you to type in new related records.

This is useful because the appropriate relationship between the two tables is created automatically
when you type into the sub-datasheet of a specific record. You can enter new data on the related
sheet on the “many” side of the relationship, as well, but would just need to make sure the foreign
key refers to an actual record that exists. In this case, it might be useful to connect the two tables
through a combo box, so that you can only input values from your associated table.
Table Relationships
In a relational database, information about a particular subject is stored in its own table. The purpose
of this is so that you do not need to store redundant data. For example, if you have a database with
information about students and classes you would want to store the information about classes
separately so that you do not have to enter all the details about a particular classsuch as time, place,
instructor, credits, etc. over again for every student enrolled in that class.

A relationship works by matching data in key columns, usually columns with the same name inboth
tables. In most cases, the relationship matches the primary key from one table, which provides a
unique identifier for each row, with the same type of field in the other table. The
inclusion of this field in the second table is called a “foreign key”. A foreign key is one or moretable
fields (columns) that refer to the primary key field or fields in another table.

After the tables are created, relationships are defined by linking the related data together through
the field(s) they have in common. In the example below, ID# in the Faculty table is the primary key
for that table. In the Contracts Table, PI is essentially the same field as ID#, containing the same
type of information. PI is a foreign key in the Contracts Table.

Note: Linking fields do not have to have the same name. They must be of the same data typeand
length for a relationship to be established, however.

In order to match that information with related data stored in another table, you must define a
relationship between the two tables. The definition of a relationship is: an association established
between common fields (columns) in two tables. In order to eventually create a relationship, you
must make sure that when you design your tables that you include a commonfield in both.

There are three types of relationships between tables. The type of relationship that is created
depends on how the related columns are defined. A relationship can be one-to-one, one-to- many,
or many-to-many.
Primary Key
Each table should have a field that constitutes a unique identifier. This field will be the table’s
primary key. Advantages of assigning a primary key:
-- an index is automatically created for the primary key. An index speeds up queries andother
operations;
-- when you view records in a form or datasheet, Access displays them in primary key
orderby default;
-- when you add data to your table, Access doesn't allow records with the same
primary keyvalue as another existing record;
-- you must specify a primary key if you want to create a default relationship between
tablesor if you want to update two or more related tables at the same time.

Types of Table Relationships


1) One-to-Many:
The most common type of relationship is the one-
to-many.In a one to many relationship a record in
Table A can have more than one matching record in
Table B, but a record in table B has at most one
matching record in Table A. An example of this
would be Orders and Employees. A singleemployee
may have sold more than one order, but a
particular customer’s order was sold by only one employee.This type of relationship is created
by including the primarykey field from the table on the one side as an additional field (foreign
key) in the table on the many side.

2) One-to-One:
In a one-to-one relationship, a row in Table A can have no more than one matching row in
Table B, and vice versa. A one-to-one relationship is created if both of the related columnsare
primary keys. This type of relationship is not common because information related in this way
would usually be included in a single table.

Examples of the use of a one-to-one relationship


would be to divide information for security
reasons, to divide a table with many columns,
store data that is short-lived ordata that applies
only to a subset of the primary table.
For example you might have one table
containinggeneral, non-confidential
information and another
containing the employee’s personal information.
The general table could be accessible to all
employees and theother could be secured to only
those in Human Resources. Usually tables in a
one-to-one relationship have the same field as a
primary key in both.
3) Many-to-Many:
In a many-to-many relationship, a row in table A may have many matching rows in table B, and
vice versa. An example of a many to many situation would be students and classes. Oneclass has
many students in it and likewise one student can have many classes.
A many-to-many
relationship between
tables is only possible
by creating a third table
(called a junction table)
whose primary key
consists of two fields –
the keys from both
Tables A and B. To
accommodate this
situation, create a
junction table
containing the primary key from Table A and the primary key from Table B. Other pertinentfields
may also be included in this table. After you have created the junction table you will then set the
relationships by creating a one-to-many relationship between Table A and the junction table and
between Table B and the junction table.

Defining Relationships Between Tables


When creating relationships between tables, the related fields do not have to have the same
names. However, related fields must have the same data type. An exception is relating an
AutoNumber field from a table with another field. An AutoNumber field may be matched with a
Number field if the FieldSize property of both fields is the same. For example, you can match an
AutoNumber field and a Number field if the FieldSize property of both fields is Long Integer.
Even when both matching fields are Number fields, they must have the same FieldSize
propertysetting.

Creating Relationships
To create a relationship between two tables:

1. Click the Relationships button on the


DatabaseTools tab.
2. Drag the field that you want to relate
from one table to the related field in the
other table. In mostcases, you drag the
primary key field (which is displayed in
bold text) from one table to a similarfield
(often with the same name) called the
foreign key in the other table.
3. The Edit Relationships dialog box is
displayed. Check the field names
displayed in the two columns to ensure
they are correct. If they are notcorrect,
you can change them here.
4. Set the relationship options if desired. For information about a specific item in the Edit
Relationships dialog box, click the question mark button, and then click the item.
5. Click the Create button to create the relationship.
When you close the Relationships window, Microsoft Access asks if you want to save the layout.
Whether you save the layout or not, the relationships you create are saved in the database.
Referential Integrity
Referential Integrity refers to rules that you can enforce to prevent the accidental changing or
deletion of data in related tables. This helps insure that your data is not out of sync and that youdo
not end up with “orphan” records, i.e., a record in one table that has lost its related information
from another table. Referential integrity also helps ensure that information in one table matches
information in another. For example, each order in the Orders table must be associated with a
specific employee in the Employee table.

Cascade Update and Cascade Delete


For relationships in which referential integrity is enforced, you can specify whether you want
Microsoft Access to automatically cascade update or cascade delete related records.

If you click to select the Cascade Update Related Fields check box when you define a relationship,
any time that you change the primary key of a record in the primary table, MicrosoftAccess
automatically updates the primary key to the new value in all related records. For example, if you
change a customer's ID in the Customers table, the CustomerID field in the Orders table is
automatically updated for every one of that customer's orders so that the relationship is not
broken. Microsoft Access cascades updates without displaying any message.

NOTE: If the primary key in the primary table is an AutoNumber field, selecting the CascadeUpdate
Related Fields check box will have no effect, because you cannot change the value inan AutoNumber
field.

If you select the Cascade Delete Related Records check box when you define a relationship, any
time that you delete records in the primary table, Microsoft Access automatically deletes related
records in the related table. For example, if you delete a customer record from the Customers
table, all the customer's orders are automatically deleted from the Orders table (this includes
records in the Order Details table related to the Orders records). When you delete records from a
form or datasheet with the Cascade Delete Related Records check box selected,Microsoft Access
warns you that related records may also be deleted. However, when you deleterecords using a
delete query, Microsoft Access automatically deletes the records in related tableswithout
displaying a warning.

Editing a Relationship
You can edit a relationship at any time and change the referential integrity rules by opening the
relationships grid and double-clicking on the relationship line between two tables. Any changesyou
make to the relationship will be automatically saved as soon as you complete the change.

Deleting a Relationship
You may wish to delete a relationship. Reasons for this could be because you need to make
changes to a related table and Access is preventing you from doing so because of the relationship
between that table and another. To delete a relationship, open the Relationships window, click
once on the relationships line and press the Delete key on the keyboard.

Access allows you to create relationships between tables so that you can query related data from
multiple tables.
In relational database terms, a relationship is a situation where multiple tables can contain related
data that is linked by a common field.
A relationship consists of a parent table and a child table. The child table references the parent
table by having a field that matches a field in the parent table. The child's field is referred to as
a foreign key. The parent's field is the primary key.
In a relationship, any data entered into the child's foreign key field must match a value from the
parent's primary key field.

By ensuring that the foreign key's data matches data in the primary key, we know that all records in
the child table will have an associated record in the parent table.
So we can create a one-to-many relationship between the Albums and Artists table. Our relationship
will determine that an artist can have many albums, but an album can only belong to one artist.

Open the Relationship Dialog

Click Relationships from the Database Tools tab on the Ribbon.


The Show Tables dialog box should
appear. If it doesn't appear, click Show
Tables.
If you have not yet created any
relationships, the Show Table dialog
box automatically appears when you
click the Relationships button.
If you have previously created a
relationship, the current relationships
will appear instead.

Select the Tables

Select both the Artists and Albums tables from the list and click Add.
Click Close to close the dialog box.

Create the Relationship

Click and drag


the Albums.ArtistId field over
the Artists.ArtistId field and release.
The Edit Relationships dialog box
appears.
Edit the Relationship

Check Enforce Referential


Integrity and click Create.
The Enforce Referential
Integrity option will ensure that
child records cannot reference a
non-existent parent.
So if a user tries to enter an album
with an ArtistId that isn't in
the Artists table, Access will
prevent them from doing so.
Access will also prevent the user
from deleting an artist that has
albums attached.
However, you can change how
Access deals with deletes and data
updates with the Cascade Update Related Fields and Cascade Delete Related Fields. Selecting these
options will delete (or update) all related records whenever a primary record is deleted/updated.
The Relationship
A diagram now appears,
representing the relationship.
Save the relationship by
pressing Ctrl+ S, right-clicking
on the tab and clicking Save, or
clicking the X icon to close the
relationship.

So now that we've established


the relationship, we can query
data across both tables and get
meaningful results. For
example, we can now look up how many albums an artist has released. Or we could find out which
artist released a given album. And more.

Types of Relationships

There are three types of relationships:

One-to-One
A row in table A can have only one matching row in table B, and vice versa.

One-to-Many (or Many-to-One)


A row in table A can have many matching rows in table B, but a row in table B can have only one
matching row in table A.
Many-to-Many
A row in table A can have many matching rows in table B, and vice versa. This is achieved through
the use of a third table (commonly called a junction table) that contains lookup data for both tables.
In this chapter, we will understand the need to create relationships between related tables. One of
the goals of good database design is to remove data redundancy.
• To achieve that goal, you divide your data into many subject-based tables so that each fact is
represented only once.
• To do this, all the common fields which are related to each other are placed in one table.
• To do this step correctly, you must first understand the relationship between your tables, and
then specify these relationships in your Access database.

Why Create Table Relationships?

MS Access uses table relationships to join tables when you need to use them in a database object.
There are several reasons why you should create table relationships before you create other
database objects, such as forms, queries, macros, and reports.
• To work with records from more than one table, you often must create a query that joins the
tables.
• The query works by matching the values in the primary key field of the first table with a
foreign key field in the second table.
• When you design a form or report, MS Access uses the information it gathers from the table
relationships you have already defined to present you with informed choices and to
prepopulate property settings with appropriate default values.
• When you design a database, you divide your information into tables, each of which has a
primary key and then add foreign keys to related tables that reference those primary keys.
• These foreign key-primary
key pairings form the basis
for table relationships and
multi-table queries.
Let us now add another table into
your database and name
it tblHRData using Table Design as
shown in the following screenshot.
Click on the Save icon as in the
above screenshot.

Enter tblHRData as table name and click Ok.


tblHRData is now created with data in it.

Let us now understand One-to-One


Relationship in MS Access. This relationship
is used to relate one record from one table
to one and only one record in another table.
Let us now go to the Database Tools tab.

Click on the Relationships option.


Select tblEmployees and tblHRData and then click on the Add button to add them to our view and
then close the Show Table dialog box.

To create a relationship between these two tables, use the mouse, and click and hold
the EmployeeID field from tblEmployees and drag and drop that field on the field we want to relate
by hovering the mouse right over EmployeeID from tblHRData. When you release your mouse
button, Access will then open the following window −

The above window relates EmployeeID of tblEmployees to EmployeeID of tblHRData. Let us now click
on the Create button and now these two tables are related.
The relationship is now saved automatically and there's no real need to click on the Save button. Now
that we have the most basic of relationships created, let us now go to the table side to see what has
happened with this relationship.
Let us open the tblEmployees table.

Here, on the left-hand side of each and every record, you will see a little plus sign by default. When
you create a relationship, Access will automatically add a sub-datasheet to that table.
Let us click on the plus sign and you will see the information that is related to this record is on
the tblHRData table.

Click on the Save icon and open tblHRData and you will see that the data we have entered is already
here.
The vast majority of your relationships will more than likely be this one to many relationships where
one record from a table has the potential to be related to many records in another table.
The process to create one-to-many relationship is exactly the same as for creating a one-to-one
relationship.

Let us first clear the layout by clicking on the Clear Layout option on the Design tab.
We will first add another table tblTasks as shown in the following screenshot.

Click on the Save icon and enter tblTasks as the table name and go to the Relationship view.

Click on the Show Table option.


Add tblProjects and tblTasks and close the Show Table dialog box.

We can run through the same process once again to relate these tables. Click and hold ProjectID from
tblProjects and drag that all the way over to the ProjectID from tblTasks. Further, a relationships
window pops up when you release the mouse.

Click the Create button. We now have a very simple relationship created.
In this chapter, let us understand Many-to-Many Relationship. To represent a many-tomany
relationship, you must create a third table, often called a junction table, that breaks down the many-
to-many relationship into two one-to-many relationships. To do so, we also need to add a junction
table. Let us first add another table tblAuthers.

Let us now create a many-to-many relationship. We have more than one author working on more
than one project and vice versa. As you know, we have an Author field in tblProjects so, we have
created a table for it. We do not need this field any more.
Select the Author field and press the delete button and you will see the following message.

Click Yes. We will now have to create a junction table. This junction table have two foreign keys in it
as shown in the following screenshot.

These foreign key fields will be the primary keys from the two tables that were linked together
— tblAuthers and tblProjects.
To create a composite key in Access, select both these fields and from the table tools design tab, you
can click directly on that primary key and that will mark not one but both of these fields.

The combination of these two fields is the tables’ unique identifier. Let us now save this table
as tblAuthorJunction.
The last step in bringing the many-to-many relationships together is to go back to that relationships
view and create those relationships by clicking on Show Table.
Select the above three highlighted tables and click on the Add button and then close this dialog box.
Click and drag the AuthorID field from tblAuthors and place it on top of
the tblAuthorJunction table AuthorID.

The relationship you’re creating is the one that Access will consider as a one-to-many relationship.
We will also enforce referential integrity. Let us now turn on Cascade Update and click on
the Create button as in the above screenshot.

Let us now hold the ProjectID, drag and drop it right on top of ProjectID from tblAuthorJunction.
We will Enforce Referential Integrity and Cascade
Update Related Fields.

The following are the many-to-many relationships.

You might also like