views:

44

answers:

1

A generic example that will help me understand database relations better:

3 tables:

| Credit Card |
| ID          |
| Card #      |

| Credit Card Type |
| ID               |
| Type             |

where CreditCardType.Type could be AMEX, Visa, MasterCard.

| Customer |
| (PK) ID  |

1.) It seems that I don't need an ID field for CreditCardType because the Type is the Primary Key defacto. Is it beneficial to have a numeric field for a PK, even though there is a varchar that is unique?

2.) Because each credit card has to have one, and only, type... Do I setup a 1:1 identifying relationship between Credit Card and Credit Card Type?

3.) A customer can have 0, 1, or more credit cards. So I create a 1:n relationship between Credit Card and Customer. When I do that, MySQL Workbench adds the Customer.ID field and the Customer.PersonTypeID field as primary keys. Is that what I should be doing, or do I only need to add the Customer.ID field as a PK. Or should it be a FK?

| Credit Card      | 
| (PK) ID          |
| Card #           |
| (PK) Customer.ID |
| (PK) Customer.PersonType |

or

| Credit Card      | 
| (PK) ID          |
| Card #           |
| (FK) Customer.ID |
+1  A: 

I would do it like this:

Customer
    Id int

CreditCardType:
    Id int
    TypeName varchar (eg. Visa)

CreditCard
    Id int
    CreditCardTypeId int
    CustomerId int
    CardNumber varchar

Eventhough you could say that a creditcard type does not need an id since the TypeName is unique, it's better to have foreign key columns that are numbers since they take up less disk space. Imagine that you had a CreditCardType "American Express" which was the primary key of the CreditCardType, you would have to use that value in the CreditCard table for each row. If you have millions of registered credit cards it would take up quite some space to store the string for each row.

klausbyskov
so for the CreditCard table, should I make it a 1:1 identifying relationship (so that CustomerID and CreditCardTypeID are primary keys), or a 1:1 non-identifying relationship so that they are FKs?
NinjaCat
@NinjaCat, I think you should make the Id column the primary key and CreditCardTypeId and CustomerId should just be foreign keys. This allows a customer to have more than one Visa card, which is probably something you want to allow.
klausbyskov
Right.... exactly...
NinjaCat
so is that a 1:1 or a 1:n relationship?
NinjaCat
@NinjaCat There is a one-to-many relationship between Customer and CreditCard, eg. a customer can have many creditcards. There is a one-to-one relationship between CreditCard and CreditCardType, eg. a CreditCard can have one type.
klausbyskov