2017-05-15 6 views
2

私はこの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対多数の関係ではなく、多対多の関係を探しています –

答えて

1
多対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関係です。 1つの店舗に複数の商品があります。 1つの製品が複数の店舗にある(おそらく)。

あなたは、これは別のテーブルで行います。これは、ジャンクションテーブルと呼ばれる

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

関連する問題