2017-05-15 39 views
2

比方說,我有這兩個表:商店和產品。我希望我的商店有一個產品清單。我怎樣才能做到這一點?如何在MySQL中創建具有N:M關係的表?

create table store(
id int unsigned not null auto_increment, 
store_name varchar(30) not null, 
product_list_FK int unsigned not null, 
primary key(id) 
); 

create table product(
id int unsigned not null auto_increment, 
product_name varchar(30) not null, 
price float not null, 
primary key(id) 
); 

我開始這樣的事情,但我不知道如何完成,你們能幫助我嗎?

+1

創建第三個表將舉行每個商店ID的產品ID。 – artm

+1

是應該是商店的孩子的產品,還是可以在許多商店出現同樣的產品?如果相同的產品可以出現在許多商店,你正在尋找一個多對多的關係,而不是一對多的關係 –

回答

1

多到一個(產品只能有一個商店)

create table store(
    id int unsigned not null auto_increment, 
    store_name varchar(30) not null, 
    primary key(id) 
); 

Query OK, 0 rows affected (0.02 sec) 

create table product(
    id int unsigned not null auto_increment, 
    store_id int unsigned not null, 
    product_name varchar(30) not null, 
    price float not null, 
    primary key(id), 
    constraint product_store foreign key (store_id) references store(id) 
); 

Query OK, 0 rows affected (0.02 sec) 

許多一對多(產品可以在許多商店)

create table store(
    id int unsigned not null auto_increment, 
    store_name varchar(30) not null, 
    primary key(id) 
); 

Query OK, 0 rows affected (0.04 sec) 

create table product(
    id int unsigned not null auto_increment, 
    store_id int unsigned not null, 
    product_name varchar(30) not null, 
    price float not null, 
    primary key(id) 
); 

Query OK, 0 rows affected (0.01 sec) 

create table product_store (
    product_id int unsigned not null, 
    store_id int unsigned not null, 
    CONSTRAINT product_store_store foreign key (store_id) references store(id), 
    CONSTRAINT product_store_product foreign key (product_id) references product(id), 
    CONSTRAINT product_store_unique UNIQUE (product_id, store_id) 
) 

Query OK, 0 rows affected (0.02 sec) 
3

這是一個n-m關係。一家商店有多種產品。一種產品在多個商店(推測)。

你有一個單獨的表做到這一點:

create table StoreProducts (
    StoreProductId int auto_increment primary key, 
    StoreId int, 
    ProductId int, 
    constraint fk_storeproducts_store foreign key (StoreId) references Stores(StoreId), 
    constraint fk_storeproducts_product foreign key (ProductId) references Products(ProductId) 
); 

這就是所謂的結表。您可以在表格中保留更多信息,例如「不再儲存」標誌或「第一批庫存日期」。

+0

明白了,謝謝你的糾正! – flpn

相關問題