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

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.

Related

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.

Creating Association between two entries in SQL table

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.

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)

Relationship between composite keyed table & non primary key table

I have two tables named ORDER_HEAD and ORDER_DETAIL, following is their structure.
ORDER_HEAD:
ORD_ID (PK)
ORD_TYPE (PK)
ORD_DATE
ORD_NET_TOTAL
ORDER_DETAIL:
ODD_ID
ODD_LINE_NO
ODD_PRODUCT_ID
ODD_QTY
I want to form a relationship between the ORD_ID in ORDER_HEAD & ODD_ID in ORDER_DETAIL table. But SQL Server shows an error message:
primary key or unique constraint must be defined for table before it can participate in a relationship
Why am I getting this error ? Is there a way to perform a join between these two columns or is there a problem in my db design ?
If you want to create a relationship from Composite primary key then any reference should also include all the column's in Composite primary key
Schema of ORDER_DETAIL should be
ORDER_DETAIL
============
ODD_ID (Fk)
ORD_TYPE(Fk) -- you need to add this column
ODD_LINE_NO
ODD_PRODUCT_ID
ODD_QTY
Create Foreign key like this.
ALTER TABLE ORDER_DETAIL
ADD CONSTRAINT FK_ORDER_DETAIL
FOREIGN KEY(ODD_ID, ORD_TYPE) REFERENCES ORDER_HEAD(ODD_ID, ORD_TYPE)
UPDATE
After rethinking the problem I think you should achieve your goal by adding reference column ODD_TYPE (like user #NoDisplayName stated) and creating composite PK for your table ORDER_DETAIL consisting of 3 columns (ODD_ID, ODD_TYPE, ODD_LINE_NO), then it would be:
ORDER_DETAIL
============
ODD_ID (PK)
ODD_TYPE (PK)
ODD_LINE_NO (PK)
ODD_PRODUCT_ID
ODD_QTY
in SQL it could be:
ALTER TABLE ORDER_DETAIL ADD CONSTRAINT PK_Order_Detail PRIMARY KEY NONCLUSTERED (ODD_ID, ODD_TYPE, ODD_LINE_NO)
Then, in ORDER_DETAIL table for specific pair (ODD_ID, ODD_TYPE) you would have records being its order lines.
I think that after removing the previous PK, adding the column and setting the above key (even in visual editor) you shouldn't have problems when creating FK between the two tables and mapping the proper columns together.

Many to many relationship with SQL Management Studio

I have the following datatypes - House, Owner, with the primary keys houseID and ownerID respectively.
An Owner can have many Houses. And a House can Have many Owners. So I created an intermediate table HouseOwner that contains two columns, houseID and ownerID.
Should I make the houseID and ownerID columns a joint primary key for the HouseOwner table?
What about creating relationships between the HouseOnwer table and the House and Owner tables, I go to Database Diagrams and add all three tables - Now should I drag houseID from the House table onto houseID from the HouseOwner table? Or should do it the other round and drag houseID from the HouseOwner table to houseID on the House table? I am unsure of which way to do it as the dialog that pops up is looking for a Primary key table and a Foreign key table.
1) Yes - Specifically, I'd do this because if you use some ORM tools (specifically EF), the many-to-many relationship would be automatically figured out when your tables are designed like this.
2) I'd suggest just doing it the old fashioned way, so you don't have to worry about the UI:
alter table HouseOwner
add constraint FK_HouseOwner_House
foreign key (HouseId)
references House (HouseId)
go
alter table HouseOwner
add constraint FK_HouseOwner_Owner
foreign key (OwnerId)
references Owner (OwnerId)
go
Question 1: I would add an additional surrogate primary key (just an identity column) but there are a lot of discussions about this.
Question 2: the foreign keys are in your HouseOwner table and they relates to the PK of house and the other foreign key to the owner table.