Database Schema Question - database

If I use the primary key of a table as the primary key of another table is it still a foreign key?
e.g.
Two tables albums and special offers
AlbumId is the primary key in both
How do I represent this relation using primary key foreign key notation?

Yes, it's still a primary key. It's usually called a one-to-one relation.
You can do something like:
create table albums (
album_id integer primary key,
-- other fields...
);
create table special_offers (
album_id integer primary key references albums(album_id),
-- other fields...
);

if e.g you have several special offers for the same album AlbumId is no longer unique in the special offers table. I would think about adding a SpecialOfferId and design a one-to-many relation.

Pablo Santa Cruz is right - yes, you're allowed to do this. However, philosophically, it's only meaningful if there really is a one-to-one relationship - all albums have one and only one special offer, and all special offers have one and only one album.
Guessing from your problem domain, that's not the case - some albums have no special offers, some have 1, some have many.
If that is indeed true, bw_üezi is right - create a one-to-many relationship.
create table albums (
album_id integer primary key,
-- other fields...
);
create table special_offers (
special_offer_id integer primary key,
album_id integer foreign key references albums(album_id),
-- other fields...
);

Related

Deal with many to many relationships in the same table

I have a table of business names and info about them, including an address column. A business name can have duplicate names and an address can have duplicates, but both the Business name and address cannot be duplicates. So there's a many to many relationship of sorts, but that is not between two tables, it's between two columns on the same table.
One or both of these fields also need to be a foreign key of another table.
Do I create a bridge table? Composite keys? If composite keys, how would I make them foreign keys in another table?
You might want to create 3 tables. One that stores the business names, another for the adresses, and then a junction table called, for example, business_adresses.
create table businesses (
id int primary key,
name varchar(50)
);
create table adresses (
id int primary key,
street varchar(200),
city varchar(200),
country varchar(200)
);
create table business_adresses(
business_id int,
adress_id int,
primary key (business_id, adress_id),
foreign key (business_id) references businesses(id),
foreign key (adress_id) references adresses(id)
);
With this set up, each entity has its own table, and information is not duplicated, unlike when using a single table. Meanwhile, in the junction table, you can efficiently enfore the unicity of business/entity tuples through the primary key (could also be a unique key), and maintain data integrity with foreign keys.

How to use the foreign key in SQL Server

I have following question: let's say we have a Chen-Notation 1:n and m:n.
So 1 has a primary key and n also, where do I type the foreign key ? in the n ?
And the second question is about m:n, both have a primary key, and I need 1 more table because it's m:n, do I type the both primary keys as foreign keys in the 3rd table?
Example of a 1:n relationship : customers and orders
One customer may have several orders. In this situation, you want a column in the orders table with a foreign key that references the primary key of the customers table.
Sample DDL:
create table customers (
id int primary key,
name varchar(50),
email varchar(50)
);
create table orders (
id int primary key
price float,
customer_id int foreign key references customer(id)
);
Example of a n:m relationship : books and authors
A book may be written by more than one author. An author may have written more than one book. You create a bridge table, also called junction table, called books_authors, to represent that relationship, and that contains foreign keys to the two other tables.
Sample:
create table books (
id int primary key,
name varchar(50)
);
create table authors (
id int primary key,
name varchar(50)
);
create table books_authors(
book_id int foreign key references books(id),
author_id int foreign key references authors(id),
constraint pk_books_authors primary key(book_id, author_id)
);
So 1 has a primary key and n also, where do I type the foreign key ? in the n ?
The foreign key lives in the n, because 1 can have many keys, but you can't have a field that holds multiple values, you need to have one value per field, so it's in the n.
And the second question is about m:n, both have a primary key, and I need 1 more table because it's m:n, do I type the both primary keys as foreign keys in the 3rd table?
Yes, because that 3rd table in effect has a many-to-one relationship to both tables.

Are composite key attributes also foreign keys?

I am working on an assignment and we are supposed to:
based on this schema:
Underlined = primary key, both underlined = composite key
My question is for the composite keys, are the two attributes that make up the composite key, as in table Borrower, also considered foreign keys?
Yes, it is possible to have a composite primary key for a table that are also considered foreign keys. If you do something like the following in SQL it would work properly.
CREATE TABLE Borrower
(
customerID VARCHAR2(10),
loan_number VARCHAR2(10),
PRIMARY KEY(customerID, loan_number),
FOREIGN KEY customerID REFERENCES Customer(CustomerID),
FOREIGN KEY loan_number REFERENCES Loan(loan_number)
);
The important thing to keep in mind is that the data type of the keys in the Borrower table have to match exactly the data types of the keys in the Customer and Loan tables respectively.

Modeling a many-to-many relationship

I have two tables, table Project and User. Below is the relationship between these two tables
A Project can be associated with multiple users
A User can operate on multiple projects
I have created below entity relationship. Is this the correct way to represent a many to many relationship?
User:
id
name
email
Project:
id
name
User_Project:
user_id
project_id
Yes, provided you have foreign key relationships (user_id) REFERENCES "user"(id) and (project_id) REFERENCES project(id) defined and a PRIMARY KEY (user_id, project_id).
BTW, try to avoid mixed case names and reserved keywords in table and column names.
Your approach is correct.
Because users can join multiple projects it is necessary to add a junction table.
Junction tables can also contain additional columns.
In your case it might be useful to know when a user joined a project.
So you could add a column join_date where you store that information.
create table users
(
id serial,
name text,
email text,
primary key (id)
);
create table projects
(
id serial,
name text,
primary key (id)
);
create table users_projects
(
user_id int,
project_id int,
join_date date,
primary key (user_id, project_id),
foreign key (user_id) references users (id),
foreign key (project_id) references projects (id)
);

When should I combine two foreign keys as a single foreign key?

My teach said I should combine two foreign keys into a single primary key. But my thought process is that that would allow for only one combination of each foreign key.
Imagine I have a Product, Purchase, PurchaseDetail.
In PurchaseDetail I have two foreign keys, one for product and one for purchase. My teacher said that I should combine these two foreign keys into a single one. But can't a product be in many different purchases? And many purchases have many products?
I'm confused.
Thanks!
Edit: This is the SQL my teacher saw and then gave feedback upon. Thanks for the guidance guys. (I changed the essential to English)
create table Purchase
(
ID int primary key identity(1,1),
IDCliente int foreign key references Cliente(ID),
IDEmpleado int foreign key references Empleado(ID),
Fecha datetime not null,
Hora datetime not null,
Amount float not null,
)
create table PurchaseDetail
(
ID int primary key identity(1,1),
IDPurchase int foreign key references Purchase(ID),
IDProductOffering int foreign key references ProductOffering(ID),
Quantity int not null
)
create table Product
(
ID int primary key identity(1,1),
IDProveedor int foreign key references Proveedor(ID),
Nombre nvarchar(256) not null,
IDSubcategoria int foreign key references Subcategoria(ID),
IDMarca int foreign key references Marca(ID),
Fotografia nvarchar(1024) not null
)
create table ProductOffering
(
ID int primary key identity(1,1),
IDProduct int foreign key references Product(ID),
Price float not null,
OfferDate datetime not null,
)
Maybe I'm confused about good database schema design. Thanks again!
I imagine he's suggesting:
Product - one primary key (product id), which implies a unique product id
Purchase - one primary key (purchase id), which implies a unique purchase id
PurchaseDetail - two foreign keys (product id),(purchase id), plus one unique constraint on (product id + purchase id)
Plus some people argue that all tables should have their own primary key that doesn't depend on anything else (purchase detail id). Some DBMS make this mandatory.
This means that you can't have two rows in PurchaseDetail that have the same product and purchase. That makes sense, assuming there is also a quantity column on PurchaseDetail, so that one purchase can have more than one of each product.
Note that there is a difference between a unique constraint and a foreign key. A foreign key merely says that there should be an item with that id in the parent table - it will let you create as many references to that item as you want in the child table. You need to specify that the column or combination of columns are unique if you want to avoid duplicates. A primary key on the other hand implies a unique constraint.
Exact syntax for defining all of this varies by language, but those are the principles.
I don't agree with the single key, but they could be a compound key (which I tend to dislike). They can be two different fields each restricted to the ID in the corresponding tables.
Not sure why the same product iD would need to be listed more than once for a single purchase? Isn't that why you indicate quantity? Maybe the need to do a separate line item for a purchase and a discount?
I believe thelem has answered correctly. But there is another option. You could add a new primary key column to the details table, so it looks like this:
detail_id int (PK)
product_id int (FK)
purchsae_id int (FK)
This is not really necessary, but it could be useful if you need to ever need to reference the details table as a foreign key - having a single primary key field makes for smaller indexes and foreign key reference (and they are a little easier to type).
That depends on what data you need to represent.
If you use the two foreign keys as the primary key for the purchase detail, a product may only occur once in each purchase. A purchase may however still contain many products, and a product may still occur in many purchases.
If the purchase detail contains more information, you may need to be able to use a product more than once in a purchase. For example if the purchase detail contains size and color, and you want to by a red T-shirt size XL and a blue T-shirt size S.
Perhaps he is suggesting a many-to-many table where it's Primary Key is comprised of the Foreign Keys to the mapped tables:
PurchaseDetail:
ProductId int (FK)
PurchaseId int (FK)
PK(ProductId, PurchaseId)
This can also be modelled as
PurchaseDetail:
PurchaseDetailId int (PK, Identity)
ProductId int (FK)
PurchaseId int (FK)
The second form is useful if you want to refer to Purchase details elsewhere in your model, and also in some RDBMS's it is beneficial to have a PK on a montonically increasing integer.

Resources