views:

77

answers:

4

Hi all,

I have a table products and table sizes. Each product can have multiple sizes. How can I design my database in order to not have repeated entries of the same product?

Thanks in advance

+2  A: 

The typical approach to a many-many relationship is to have a mapping table called Product_Size that contains the Primary Keys of each table.

create table Product (
    id uniqueidentifier not null,
    name varchar(255),
    primary key (id))

create table Size (
    id int,
    name varchar(255),
    primary key (id))

create table Product_Size (
    productId uniqueidentifier,
    sizeId int,
    primary key (productId, sizeId),
    foreign key (productId) references Product(id),
    foreign key (sizeId) references Size(id))
Justin Niessner
Except I would not use a unique identifer as the PK in a table for perfornance reasons unless I had no other choice. An INT is a better choice most of the time.
HLGEM
+1  A: 
product Table

 1. product id 
 2. product name
 ......

Product Size

 1. Id
 2. ProductId( Foreign key form product table)
 3. Size 
Pranay Rana
+1  A: 

It depends, each product can have multiple sizes, but can different products have the same size?

If they can't then you have a one-many relationship and you need a ProductSize table which holds the primary key of the product.

ProductSize (SizeID, ProductID, Size)

If they can then you have a many to many relationship and you can break this up by having three tables, Product, Size and ProductSize, where Product contains products, Size contains sizes and ProductSize maps each product to the sizes available, by holding the primary key of Product and Size.

Product (ProductID, ProductName)
Size (SizeID, SizeName)
ProductSize (ProductID, SizeID)
Chris Diver
A: 

try something like this:

Products
----------
ProductID    PK, auto increment int
ProductName
....

Sizes
------- 
SizeID      PK, auto increment int
SizeInfo
....

ProductSizes
--------------
ProductID   PK, FK to Products.ProductID
SizeID      PK, FK to Sizes.SizeID
KM