Click here to Skip to main content
15,908,111 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am given a task to implement “related products” functionality in an existing database. Since I am a SQL Server novice and not sure how to complete this task I was wondering if there is a solution like adding another column to existing database - RelatedProductID. Our products table is like this:

ProductID int, PK
Name nvarchar(100)
Price decimal
CoverImageURL nvarchar(400)
-- there are couple more columns
Posted
Comments
Karthik Harve 18-Apr-13 4:35am    
Your is not clear. are you asking how to add new column for the existing database table ?

The problem with that idea is that it does two things:
1) it restricts the number of "related products" you can have to a single item - if you look at somewhere like Amazon, that isn't often the case. If you buy a phone, you probably want a cover and a hands free kit for example. Conversely, a handsfree kit may apply to a dozen phones.
2) It makes it a pain to remove a product, because you have to check every other product to see if it is a related product of that as well.

There are two approaches I would consider: a separate table to hold a link between product and it's related item, or a relation group table where a group would hold say six related items. It depends how many items you are talking about, and how many relations you will be involving.
 
Share this answer
 
Yes, there is a solution like you mentioned but it’ll only work if there is exactly one related product for each of your products.
However, if this is not the case you’ll need referencing table containing all relations between products.

You can try adding a new table:
CREATE TABLE dbo.ProductsRelation
(
    FirstProductId int not null,
    SecondProductId int not null,
    PRIMARY KEY (FirstProductId, SecondProductId)
)

In this way, you can retrieve all related products for some product with the query below:
SELECT SecondProductId
FROM ProductsRelation
WHERE FirstProductId = @ProductID
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900