gpt4 book ai didi

mysql - 如何使用 N :M relationship in MySQL? 创建表

转载 作者:搜寻专家 更新时间:2023-10-30 19:59:03 24 4
gpt4 key购买 nike

假设我有这两个表: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)
);

我开始了类似的事情,但我不知道如何结束,你们能帮帮我吗?

最佳答案

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

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)

关于mysql - 如何使用 N :M relationship in MySQL? 创建表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43990459/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com