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

标签 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)
);

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

最佳答案

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

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/

相关文章:

sql - 我的 Oracle TRIGGER 出了什么问题?

mysql - 如何创建 2 列 SQL View ?

java - 使用 Java 在 MySQL 中存储 HTML

php - 设置一个 MySQL 表来跟踪用户链接点击

php - 使用来自多个表的信息输入新的/编辑现有的数据库记录

java - 删除操作未发生批量执行

php - 表单提交处理和生成

java - Mybatis如何运行sql "desc table"

sql - 范围和分配单元之间有什么区别/关系?

database - 使用 VB6 Access 远程数据库