#商品表
create table goods(
id int not null auto_increment primary key,
goods_name int not null default 0 comment '商品名称',
price int not null default 0 comment '商品价格'
)
insert into goods (goods_name,price)values('苹果手机','5000');
insert into goods (goods_name,price)values('小米手机','8000');
#属性表
create table attr(
id int not null auto_increment primary key,
catid int not null default 0 comment '类型ID',
pid int not null default 0 comment '父ID',
name char(20) not null default '' comment '属性或者规格名称'
)
insert into attr (catid,pid,name)values(1,0,'重量');
insert into attr (catid,pid,name)values(1,1,'15g');
insert into attr (catid,pid,name)values(1,1,'20g');
insert into attr (catid,pid,name)values(1,0,'颜色');
insert into attr (catid,pid,name)values(1,4,'红色');
insert into attr (catid,pid,name)values(1,4,'黑色')
id catid pid name
1 1 0 重量
2 1 1 15g
3 1 1 20g
4 1 0 颜色
5 1 4 红色
6 1 4 黑色
#商品属性保存关联表
create table goods_attr(
id int not null auto_increment primary key,
catid int not null default 0 comment '分类ID',
goodsid int not null default 0 comment '商品ID',
attrid int not null default 0 comment '属性ID',
attr_value_id int not null default 0 comment '属性值ID'
)
第一个商品 参数-重量:15g 颜色:红色
第二个商品 参数-重量:15g 颜色:黑色
id catid goodsid attrid attr_value_id
1 1 1 1 2
2 1 1 4 5
3 1 2 1 2
4 1 2 4 6
insert into goods_atrr(catid,goodsid,attrid,attr_value_id)values(1,1,1,2);
insert into goods_atrr(catid,goodsid,attrid,attr_value_id)values(1,1,4,5);
insert into goods_atrr(catid,goodsid,attrid,attr_value_id)values(1,2,1,2);
insert into goods_atrr(catid,goodsid,attrid,attr_value_id)values(1,2,4,6)
我现在要查第一个参数:要求查重量等于15g的商品 ,传入搜索参数 重量属性ID(1)和重量属性值ID (2)
select goodsid from goods_attr where catid = 1 and attrid = 1 and attr_value_id = 2
第一个条件检索 得到商品ID为 1 2 的商品(两个商品)
那下面要再加一个参数:要求查出 重量等于15g的商品 和 颜色等于黑色的商品
首先把重量的属性ID,属性值ID传过去,然后再把颜色属性ID,颜色属性值ID传过去(4,6)
然后去查询(分两次查询,每个属性查询一次):
select goodsid from goods_attr where catid = 1 and attrid = 1 and attr_value_id = 2
结果商品ID: 1,2
select goodsid from goods_attr where catid = 1 and attrid = 4 and attr_value_id = 6
结果商品ID: 2
得到两组数据,最后在两组数据里找到两次属性筛选都符合的商品,查出商品信息
select * from goods where id in(1,2) and id in(2) order by id;
结果商品ID: 2