Question

I have a question regarding cardinality between two tables. I'm not sure how to approach it.

Imagine the following:

There are groups: group 1, group 2, group 3 etc

One group can have multiple items and those items can be only in one of those groups. A store can have only one group of items and one group can be in one store at a time, so you can say a store posseses a group. This being like this, group and store would have a cardinality of 1:1. However, over time groups will change between stores, so every stroe will change the group it has, but groups wont repeat over stores. Sö, stores will interchange groups every now and then.

The problem is I'm not sure if it still is 1:1 or it can be considered as a 1:N, if you think it as a long term thing over time, more so if I want to register the date of the change.

Also, this whole thing results in a kind of ternary relationship, since stores can sell multiple items which at the same time are in a group and only in 1 group of items, but this groups are possed only by one store at a time, but, this stores will exchange groups over time. So this is making my head explode.

Was it helpful?

Solution

I think you might be missing an entity in your model. Over time a store can be associated with multiple groups and a group can be associated with multiple stores, so unless you only want to record the current state and no history you have a N:M relationship and need a junction table. Something like:

Store      StoreGroup                        Item
=====      ==========       Group            =============
Id   <---- StoreId          ==========       Id
           GroupId    ----> Id         <---- GroupId
           StartTime        GroupProp1       ItemProperty1
           EndTime          GroupProp2       ItemProperty2

You may need to enforce the "one store has one group at a time" rule in your application layer unfortunately, or using triggers, I'm not sure SQL constraints will be sufficient.

As an alternative to directly modelling changes over time, if the database you are using supports temporal tables (sometimes called "system versioned") you could use that feature instead.

Then you can have:

Store      Group            Item
=====      ==========       =============
Id   <---- StoreId          Id
           Id         <---- GroupId
           GroupProp1       ItemProperty1
           GroupProp2       ItemProperty2

and one group has one store is enforced by only being able to have one store in the data for a group, and one group per store can be enforced by a unique constraint on Group.StoreId. But I might recommend the other approach unless you can guarantee that the one-group-one-store rule will hold for future versions (it seems unusually limiting to my mind), as the former approach would be easier to refactor to allow the greater flexibility.

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top