如何在 MySQL 中创建具有 N:M 关系的表?

flp*_*lpn 8 mysql sql database

假设我有这两个表:Store 和 Product。我希望我的商店有一个产品清单。我怎样才能做到这一点?

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)
);
Run Code Online (Sandbox Code Playgroud)

我开始了这样的事情,但我不知道如何完成,你们能帮我吗?

小智 11

多对一(产品只能有一个店铺)

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)
Run Code Online (Sandbox Code Playgroud)

多对多(产品可以在多个商店)

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)
Run Code Online (Sandbox Code Playgroud)


Gor*_*off 5

这是一个 nm 关系。一家商店有多种产品。一种产品有多个商店(大概)。

您可以使用单独的表来执行此操作:

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)
);
Run Code Online (Sandbox Code Playgroud)

这称为联结表。您可以在表中维护其他信息,例如“不再库存”标志或“首次库存日期”。