一个数据表查询问题

产品表

image.png

产品属性表
image.png

前端查询页面图
image.png

这时候 突然不知道前端 点击某些筛选之后 sql语句该怎么写了~~ 表结构貌似有点问题?

如上面查询图 现在要查 所有产品 颜色 = 金色 成色 = A+

select * from product_attr where `key` = 'color' and `value` = '金色' // 这样是ok的 那再加上 成色呢?
select * from product_attr where `key` = 'colour' and `value` = 'A+' 

怎么把上面那两条sql语句 合起来呢? 查询 成色 = A+ 且 颜色 = 金色的产品 突然脑子有点转不过来了。

阅读 3.6k
4 个回答

你的表设计有问题,应该直接把颜色、成色这些作为产品表的字段,属性表直接拿掉不要了。

这种情况下需要用交集,取出两部分重合的数据

这个sql 应该可以满足你的需求,但是在真正的产品中,是不会出现这种的sql的
你这个表设计得有问题,你可以去了解一下商品的sku的设计


SELECT product.* from product LEFT JOIN(
SELECT t1.product_id FROM ( SELECT * FROM product_attr WHERE key = 'color' AND `value` = '金色' ) t1
JOIN ( SELECT * FROM product_attr WHERE `key` = 'colour' AND `value` = 'A+' ) t2 ON t1.product_id = t2.product_id
) temp  on product.id = temp.product_id

最后的解决方案

select * from  `product`  where  exists (select  `product_id`  from  `product_attr`  where  `product`.`id` = `product_attr`.`product_id`  and  `key` in ('storage', 'color') and  `value` in ('128G', '白色') group  by  `product_id`  having  count(id) >= 2)

核心是在 group by porduct_id having count(id) >= 2这里 如果查询条件是3个那么 count(id) >=3 依次类推
暂未发现什么坑 能完成需求

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题