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

Let's say I have this two tables: Store and Product. I want my store to have a list of products. How can I do that?

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)

);

I started something like that, but I don't know how to finish, can you guys help me?

解决方案

Many-to-one (products can only have one store)

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)

Many-to-many (products can be in many stores)

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值