This is one of the most typical question asked by the interviewers.
Let’s us assume that we have the following two table of Product and Vendor with their respective fields like below.
ProductId ProductName Cost //Product table
VendorID VendorName ProductId //Vendor table
Now let’s begin with how you can design one to one relationship between these two tables.
One to One relationship:-
Below diagram show one to one relationship between Product and Vendor table.
In the above Product table “ProductId” is defined as a primary key and in the Vendor table “ProductId” is defined as foreign key with reference to the “ProductId” of the Product table.
In this way you can achieve one to one relationship.
One to Many relationship:-
Now we want to define one to many relationship on Vendor and Product table.
In this many records in one table correspond to the one record in another table.
Example: Every one vendor can have multiple products. So there exist one-to-many relationships between Vendor and Product table.
In order to define one to many relationship you have to add one column name as VendorId in Product table which is foreignkey reference to VendorId of Vendor table.
Below diagram show one to many relationship on Product and Vendor table.
Many to Many relationship:-
In this, one record in one table corresponds to many rows in another table and also vice-versa.
For instance: In a company, one vendor can sale many products and also one product can be sold by many Vendors.
Given below diagram is a sample of many-to-many relationship. For defining many to many we have to add one more table VendorProduct which is linked to the primary key of Product and Vendor tables.
In the following video, view samples of various questions asked in C#, .NET and Sql Server interview.
Asked In: Many Interviews |