Creating Association between two entries in SQL table - sql

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.

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.

Related

how to make multiple foreign keys between two tables?

I am using sql server management studio and I have two tables, "City" and "Booking". In the booking table, there are two columns, "SourceCity" and "DestinationCity". I want to take two foreign keys from city table to Booking table for the above mentioned columns, but I don't know how to do it. I want to use this all for a stored procedure for adding new bookings as well. please help me out here.
I guess, youcan try something like this:
ALTER TABLE Booking
ADD CONSTRAINT FK_BookingSourceCity
FOREIGN KEY (SourceCity)
REFERENCES City (CityName);
ALTER TABLE Booking
ADD CONSTRAINT FK_BookingDestinationCity
FOREIGN KEY (DestinationCity)
REFERENCES City (CityName);
I assume CityName is a primary key in the table City

How to create associative table where one of the fields is not primary key?

I am structuring a postgres database.
I have two tables, products (coke) and optional (with ice, lemon ...), that is, a relationship many to many.
An associative table is usually built using the primary keys of the tables, correct? However, in my case, there is a specific feature ... due to some imports from other databases...I have two ids fields (id and "externalId"), one primary key and one common ... one is the local id of my bank and the other represents the id that the item has in the bank from which it was imported.
I need an associative table between "externalId" and a primary key from another table.
ExternalId is not a primary key...
ALTER TABLE public.opcional_produto
Add
CONSTRAINT idproduto_fkey FOREIGN KEY (prod_id) REFERENCES public.produto (prod_idExt)
ERROR: there is no unique constraint matching given keys for
referenced table "produto" SQL state: 42830
How can I do?
If externalid is unique, you should create a unique constraint:
ALTER TABLE produto ADD UNIQUE (externalid);
Ideally it should also be not nullable:
ALTER TABLE produto ALTER externalid SET NOT NULL;
Now it can be used as target of a foreign key.

How to setup tables with varying number of Foreign Key of specific type

Say I have three tables.
MenuItem(MenuItemID{PK}, MenuItemName, MenuItemIngredient)
Ingredient(IngredientID{PK}, IngredientName, SupplierID)
Supplier(SupplierID{PK}, SupplierName)
Each MenuItem in the MenuItem table can have multiple ingredients.
Each Ingredient in the Ingredient table can have multiple suppliers.
My current way of doing this is to have two extra tables.
MenuIngredientLink(MenuItemID{PK}, IngredientID{FK})
IngredientSupplierLink(IngredientID{PK}, SupplierID{FK})
Then remove the last column on MenuItem and Ingredient tables.
This doesn't really seem like a good way to do it though.
Any alternatives?
Fairly new to SQL so any help would be appreciated.
Using Microsoft SQL Server 2014.
Since everything follows a strict one-to-many relationship,your original approach to the problem is correct.So no need to introduce two mapping tables.
However, a problem arises in a scenario like this. An ingredient is supplied by many suppliers as well as a supplier provides multiple ingredients, creating a many-to-many relationship.Then your approach to a mapping table is the preferred solution.
I have included an external source for your reference. Hope this helps.
Managing Database Relationships
We can make tables with foreign keys as you've specified. If you start with the Supplier table, you should insert all values required, and it has no foreign key so you have no restrictions. Next, you insert values into the Ingredients table, since it requires a foreign key to Suppliers. Lastly, you insert values into the MenuItem table, since it has a foreign key to Ingredient. You can create the tables first, then add the foreign keys later as I've written below.
--Suppliers does not have any foreign keys
CREATE TABLE Supplier (SupplierID int PRIMARY KEY, SupplierName varchar(100))
--Ingredients has a foreign key to Supplier(SupplierID)
CREATE TABLE Ingredient (IngredientID int PRIMARY KEY
, IngredientName varchar(100)
, SupplierID int)
ALTER TABLE Ingredient ADD FOREIGN KEY (SupplierID) REFERENCES Supplier(SupplierID)
--MenuItem has a foreign key to Ingredient(IngredientID)
CREATE TABLE MenuItem (MenuItemID int PRIMARY KEY
, MenuItemName varchar(100)
, MenuItemIngredientID int)
ALTER TABLE MenuItem ADD FOREIGN KEY (MenuItemIngredientID) REFERENCES Ingredient(IngredientID)

Relation from one table to another with two columns in the primary key in SQL Server

I am trying to make a relation from a table to another like the following :
Books
IdBook (primary)
SerialNumber (primary)
NameBook
The other table is :
Qtt
IdQtt (primary)
IdBook
Qtt
How can I make a relation only between Qtt.IdBook and Books.IdBook ?
You meant to create a FOREIGN KEY relationship between the tables on that column like
CONSTRAINT FK_idbook FOREIGN KEY (IdBook)
REFERENCES Books (IdBook)
ON DELETE CASCADE
ON UPDATE CASCADE
But that will not work since you have composite PK in your Books table on IdBook, SerialNumber and thus you need another key column in your Qtt table to refer to both PK column else it would be a PFD (partial functional dependency)
constraint FK_book FOREIGN KEY (IdBook,IdQtt) references Books (IdBook,SerialNumber)
Although it is technically possible to create a UNIQUE constraint on Books.IdBook and a FOREIGN KEY constraint on Qtt.Book referencing that column, this probably won't work with your data model because IdBook alone doesn't uniquely identify a Books row. You need a table like BookTitle keyed by IdBook, with a one-to-many relationship to Books and another one-to-many relationship from BookTitle to Qtt on IdBook.

SQL Foreign Key Redundancy

This is a question about foreign key redundancy
redundant foreign key? <- Similar Question
In General:
A Foreign Key from TABLE C references a Primary Key from Table B
A Foreign Key From Table C references a Primary Key from Table A
A Foreign Key from Table B references a Primary Key from Table A
Is the Foreign Key from C -> A necessary since C is connected through B to A?
Specific: 3 tables
Supplier Info Table A
Supplier ID - PK
Person Contact Info (for supplier) Table B
Part # - PK
Date Received - PK
Supplier ID - FK
Part Rprt Table C
Part # - PK & FK
Date - PK & FK
Supplier ID - FK
Thanks - Suggestions for reworking all the table are also welcome
The key would technically be redundant if you assume that the supplier for a person is always the supplier represented by the part. Remember, that things can change over time. Presumably, suppliers could merge, persons could change the supplier they are associated with, and the supplier associated with a part could change.
The data structure, however, does not look properly normalized. I would think that you would want a person table with information only about the person. I don't get the relationship between parts and persons.
So, I think you should rework your data structure. I would suggest that you start with the entities you have identified -- suppliers, persons, and parts. Then create association tables for them, if necessary. It is quite possible that each person should just have a SupplierId and each part should have a SupplierId and that models the relationships. If there is a relationship between parts and persons, then you might be able to satisfy that with just a PersonId field in parts.