0

I have a piece of work to do setting up a database for a small enterprise.

Currently I have 5 tables set up:

  • Customers
  • Accounts
  • Associations
  • Security(Collateral)
  • References (Reference Codes relating to a Job type)

One of the tasks I have is to create an association table that will link to the Customers table and show the association between 2 customers.

Columns for Association table:

  • AssociationID
  • Customer1
  • AssociationType
  • Customer2

The output should be "Customer1 is AssocationType of Customer2" eg "Dave is Accountant for Jim"

How do I set it up so that Customer1 & Customer2 are from the Customer's table? I think it might be with Foreign Keys but I am unsure.

Dave
  • 5,108
  • 16
  • 30
  • 40
NH92
  • 9
  • 1
  • (Obviously--) This is a faq. Before considering posting please always google any error message & many clear, concise & precise phrasings of your question/problem/goal, with & without your particular strings/names; read many answers. If you post a question, use one phrasing as title. See [ask] & the voting arrow mouseover texts. PS Time to read a published academic textbook on information modelling, the relational model & DB design. (Manuals for languages & tools to record & use designs are not textbooks on doing information modeling & database design.) – philipxy Jun 02 '19 at 04:26
  • Possible duplicate of [How to create relationships in MySQL](https://stackoverflow.com/questions/260441/how-to-create-relationships-in-mysql) – philipxy Jun 02 '19 at 04:28

1 Answers1

0

You can set up foreign keys:

alter table associations add constraint fk_associations_customer1
    foreign key (customer1_id) references customers (customer_id);

alter table associations add constraint fk_associations_customer2
    foreign key (customer2_id) references customers (customer_id);

Foreign keys should be made to the primary key, so you need to define customers so:

create table customers (
    customer_id int primary key, -- perhaps identity, serial or autoincrement depending on your database
    . . .
);

You'll note the naming conventions:

  • Tables are in the plural (the contain multiple examples of something).
  • The primary key is the singular followed by _id.
  • The foreign key is either the same name as, or very similar to, the primary key of the referenced table.
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786