Many to many relationship with SQL Management Studio - sql

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.

Related

SQL Server use same Guid as primary key in 2 tables

We have 2 tables with a 1:1 relationship.
1 table should reference the other, typically one would use a FK relationship.
Since there is a 1:1 relationship, we could also directly use the same Guid in both tables as primary key.
Additional info: the data is split into 2 tables since the data is rather separate, think "person" and "address" - but in a world where there is a clear 1:1 relationship between the 2.
As per the tags I was suggested I assume this is called "shared primary key".
Would using the same Guid as PK in 2 tables have any ill effects?
To consolidate info from comments into answer...
No, there are no ill effects of two tables sharing PK.
You will still need to create a FK reference from 2nd table, FK column will be the same as PK column.
Though, your example of "Person" and "Address" in 1:1 situation is not best suited. Common usage of this practice is entities that extend one another. For example: Table "User" can hold common info on all users, but tables "Candidate" and "Recruiter" can each expand on it, and all tables can share same PK. Programming language representation would also be classes that extends one another.
Other (similar) example would be table that store more detailed info than the base table like "User" and "UserDetails". It's 1:1 and no need to introduce additional PK column.
Code sample where PK is also a FK:
CREATE TABLE [User]
(
id INT PRIMARY KEY
, name NVARCHAR(100)
);
CREATE TABLE [Candidate]
(
id INT PRIMARY KEY FOREIGN KEY REFERENCES [User](id)
, actively_looking BIT
);
CREATE TABLE [Recruiter]
(
id INT PRIMARY KEY
, currently_hiring BIT
, FOREIGN KEY (id) REFERENCES [User](id)
);
PS: As mentioned GUID is not best suited column for PK due to performance issues, but that's another topic.

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 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.

MS SQL creating many-to-many relation with a junction table

I'm using Microsoft SQL Server Management Studio and while creating a junction table should I create an ID column for the junction table, if so should I also make it the primary key and identity column? Or just keep 2 columns for the tables I'm joining in the many-to-many relation?
For example if this would be the many-to many tables:
MOVIE
Movie_ID
Name
etc...
CATEGORY
Category_ID
Name
etc...
Should I make the junction table:
MOVIE_CATEGORY_JUNCTION
Movie_ID
Category_ID
Movie_Category_Junction_ID
[and make the Movie_Category_Junction_ID my Primary Key and use it as the Identity Column] ?
Or:
MOVIE_CATEGORY_JUNCTION
Movie_ID
Category_ID
[and just leave it at that with no primary key or identity table] ?
I would use the second junction table:
MOVIE_CATEGORY_JUNCTION
Movie_ID
Category_ID
The primary key would be the combination of both columns. You would also have a foreign key from each column to the Movie and Category table.
The junction table would look similar to this:
create table movie_category_junction
(
movie_id int,
category_id int,
CONSTRAINT movie_cat_pk PRIMARY KEY (movie_id, category_id),
CONSTRAINT FK_movie
FOREIGN KEY (movie_id) REFERENCES movie (movie_id),
CONSTRAINT FK_category
FOREIGN KEY (category_id) REFERENCES category (category_id)
);
See SQL Fiddle with Demo.
Using these two fields as the PRIMARY KEY will prevent duplicate movie/category combinations from being added to the table.
There are different schools of thought on this. One school prefers including a primary key and naming the linking table something more significant than just the two tables it is linking. The reasoning is that although the table may start out seeming like just a linking table, it may become its own table with significant data.
An example is a many-to-many between magazines and subscribers. Really that link is a subscription with its own attributes, like expiration date, payment status, etc.
However, I think sometimes a linking table is just a linking table. The many to many relationship with categories is a good example of this.
So in this case, a separate one field primary key is not necessary. You could have a auto-assign key, which wouldn't hurt anything, and would make deleting specific records easier. It might be good as a general practice, so if the table later develops into a significant table with its own significant data (as subscriptions) it will already have an auto-assign primary key.
You can put a unique index on the two fields to avoid duplicates. This will even prevent duplicates if you have a separate auto-assign key. You could use both fields as your primary key (which is also a unique index).
So, the one school of thought can stick with integer auto-assign primary keys, and avoids compound primary keys. This is not the only way to do it, and maybe not the best, but it won't lead you wrong, into a problem where you really regret it.
But, for something like what you are doing, you will probably be fine with just the two fields. I'd still recommend either making the two fields a compound primary key, or at least putting a unique index on the two fields.
I would go with the 2nd junction table. But make those two fields as Primary key. That will restrict duplicate entries.