Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database relationship cycle

Database relationship cycles smell like bad database design. Below is a situation in which I think it can not be prevented:

  • a Company has Locations (City)
  • a Company has Products (Big Mac)

  • Products are/are not available on Locations (No Bacon Burger in Saudia Arabia)

The current design would allow you to offer a Product that doesn't belong to this Company on a Location that does belong to this Company.

Company
1 - McDonalds
2 - Burger King

Location
1 - New York, building 1 - McDonalds (1)
2 - Amsterdam, building 2 - Burger King (2)

Product
1 - Big Mac - McDonalds (1)

ProductLocation
1 - Big Mac (1) - Amsterdam, building 2 (2)

McDonalds sells Big Macs, Burger King doesn't, but it seems their building does :)
It becomes worse when we add relationships to Product that are also Location dependent.

What can I do to prevent the cycle?
How do I ensure database data integrity?

like image 983
Zyphrax Avatar asked May 25 '11 10:05

Zyphrax


People also ask

What are the 3 types of relationships in a database?

There are 3 different types of relations in the database: one-to-one. one-to-many, and. many-to-many.

What are the 5 phases of database design?

Logical design. Physical design. Implementation. Monitoring, modification, and maintenance.

What are the phases of database life cycle?

The Database Life Cycle (DBLC) contains six phases, as shown in the following Figure: database initial study, database design, implementation and loading, testing and evaluation, operation, and maintenance and evolution.


2 Answers

Cyclic dependencies are not automatically "bad database design". From a conceptual modelling point of view if such a dependency accurately represents what you are trying to model then it isn't "wrong".

Unfortunately the limitations of SQL often make it hard or impossible to enforce constraints that are cyclical. In SQL you will usually have to compromise by breaking the constraint in some way or by implementing the rule in procedural code rather than through database constraints.

like image 160
nvogel Avatar answered Oct 12 '22 00:10

nvogel


If we start with Location, Company and Product as independent entities -- as I think you tried to:

enter image description here

create table ProductAtLocation (
      CompanyID  integer
    , LocationID integer
    , ProductID  integer
);

alter table ProductAtLocation
    add constraint pk_ProdLoc  primary key (CompanyID, LocationID, ProductID)
  , add constraint fk1_ProdLoc foreign key (CompanyID, LocationID) references CompanyLocation (CompanyID, LocationID)
  , add constraint fk2_ProdLoc foreign key (CompanyID, ProductID)  references CompanyProduct  (CompanyID, ProductID)
;

And if the Product is a dependent entity (depends on company):

enter image description here

like image 29
Damir Sudarevic Avatar answered Oct 12 '22 02:10

Damir Sudarevic