简体   繁体   中英

Best way to normalize this data

I have two tables, 'Product' and 'Product Packs'.

One product can appear in many product packs and a product pack can have many products (A many to many relationship).

I have also created a linking table to try and resolve this relationship but I am left with the following conundrum:

-------------------
|  Linking table  |
-------------------
| Prod_Id | PP_id |
|  1      |  3    |
|  1      |  4    |
|  1      |  5    |
|  1      |  6    |
|  1      |  7    |
|  2      |  5    |
|  2      |  7    |
|  2      |  8    |
|  2      |  10   |
|  2      |  4    |

Is this normal practice for database design? Could this be refined further?

You have a good starting point.

Taking it here you should consider, making the two fields of the table into a composite primay key. That would prevent duplicate records as noted by @musical_coder.

You might also consider adding an integer column that indicates the quantity of products in the package.

Finally, you might want to add some metadata columns such as CreatedWhen, CreatedBy, LastUpdatedWhen, and LastUpdatedBy. These tend to come in handy from time to time.

In my experience I would say that's no problem with this kind of relationship, but you need to be very careful when , but how you model is logical that a product is in a package and a package contains n products. 时需要非常小心,但是如何建模是合乎逻辑的,产品在包装中,包装包含n种产品。 So that's not bad.

Edit: This is an obsolete answer since the poster fixed his example data to not contain duplicate tuples anymore

From a database normalization perspective, this design is a bit tricky: If having two identical tuples in that table is supposed to have a meaning (eg, a count), then this table has a multi-set semantics, which does not mix well with the relational model, since you don't have a key.

Having a table (Prod_ID, PP_Id, Count) with primary key (Prod_ID,PP_Id) is be a better (third normal form) design.

Edit:

So your table becomes

create table t (Prod_Id int, PP_Id int, Count int, primary key(Prod_Id,PP_Id));

insert into t values 
(1,3,2),
(1,4,1),
(1,5,1),
(1,6,1),
(1,7,1),
(2,5,1),
(2,7,1),
(2,8,1),
(2,10,1),
(2,4,1);

select * from t;

Prod_Id     PP_Id       Count
----------  ----------  ----------
1           3           2
1           4           1
1           5           1
1           6           1
1           7           1
2           5           1
2           7           1
2           8           1
2           10          1
2           4           1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM