假设我有两个表:商店和产品。我希望我的商店有一个产品清单。我怎么能这样做?
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)
);
我开始做类似的事,但我不知道如何完成,你们可以帮助我吗?
答案 0 :(得分:3)
这是一种n-m关系。一家商店有多种产品。一种产品在多个商店(据推测)。
您可以使用单独的表格执行此操作:
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)
);
这称为联结表。您可以在表格中保留其他信息,例如"不再存储" flag或"第一批股票的日期"。
答案 1 :(得分:2)
多对一(产品只能有一个商店)
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)