用php的项目多吗,php – 使用一个项目保存多个类别

我正在建立一个网站,您可以在其中添加多个类别的项目.

在一个字段中存储多个类别并保持字段可搜索的最佳方法是什么?

解决方法:

您不在一个字段中存储多个类别,而是创建一个单独的表来为每个项目分配类别.与此类似:

-- create your table to store items/products

create table items

(

id int, -- this will be the PK

name varchar(10)

);

insert into items values

(1, 'product1'),

(2, 'product2');

-- create your table to store categories

create table categories

(

id int, -- this will be the PK

name varchar(50)

);

insert into categories values

(1, 'color'),

(3, 'material'),

(6, 'size');

-- create your join table to assign the categories to each item

-- this table will have a foreign key relationship to the items and categories table

create table items_categories

(

item_id int, -- both fields will be the PK

category_id int

);

insert into items_categories values

(1, 1),

(2, 3),

(2, 6);

然后,您将通过连接表来查询数据:

select i.id itemid,

i.name item,

c.name category

from items i

left join items_categories ic

on i.id = ic.item_id

left join categories c

on ic.category_id = c.id

标签:php,sql,database-design

来源: https://codeday.me/bug/20190723/1511575.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值