简体   繁体   中英

Is my database design correct?

I have tables called: 1. Mall 2. Store 3. Product

Mall can obviously have multiple stores and stores can have multiple products. So should this be an identifying relationship because a store can't exist without a mall and products can't exist without belonging to a store (at least I don't want them to)?

Also what is confusing to me that if I create this design with MySQL Workbench (even though I am using SQLite in my project) it will create 3 primary keys in the Product table, 2 of them referencing the tables before. Shouldn't the Product table only have a reference to the Store table as it's the step before?

How would I query in a database design like this for a product that has a specific name and it exists in a mall that has stores "Store 1" and "Store 2"?

Thanks!

You must avoid repeated dependencies in the database. You have the following database structure.

Mall --> (1:n) Store --> (1:n) Product 

and per your design, the dependency of the product does not exist without a store. A mall cannot contain the product without a store, right?

Mall -->  (1:n) Product  {Cannot exist}

Hence, there is no point in adding mall foreign key to product table. Here isa sample SQL statements for your db structure.

    create table if not exists mall (
mall_id int(11) AUTO_INCREMENT PRIMARY KEY,
mall_name varchar(255) NOT NULL
)

create table if not exists store (
store_id int(11) AUTO_INCREMENT PRIMARY KEY,
store_name varchar(255) NOT NULL,
mall_id int(11) ,
CONSTRAINT 'mall_Id_FK' FOREIGN KEY (mall_id) REFERENCES mall(mall_Id)  ON UPDATE CASCADE  ON DLETE CASCADE
);

create table if not exists product (
product_id int(11) AUTO_INCREMENT PRIMARY KEY,
product_name varchar(255) NOT NULL,
store_id int(11) ,

CONSTRAINT 'store_Id_FK' FOREIGN KEY (store_id) REFERENCES store(store_id) ON UPDATE CASCADE  ON DLETE CASCADE
);

Also regarding you question that how would you qyery product data based on store and mall :

How would I query in a database design like this for a product that has a specific name and it exists in a mall that has stores "Store 1" and "Store 2"?

Is

    SELECT a.product_id, a.product_name 
from product a ,
store b,
 mall c 
where
 a.store_id = b.store_id and 
 b.mall_id= c.mall_id and
 c.mall_name = 'Mall1' and
 b.store_name IN ('Store1' ,'Store2') and 
 a.product_name = 'Product1';

This return the product detail in a specific mall under a specific store.

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