我有一个这样的表结构
Products{id, name}
ProductProperties{id, product_id, property, value}
示例数据如下
Products
id name
1 p1
2 p2
ProductProperties
id product_id property value
1 1 brand nike
2 1 model xl
3 1 brand nike
4 1 model xl
现在我想要查询brand是nike,而且model是xl的product
直观的sql语句:
select * from ProductProperties pp
where (pp.property = 'brand' and pp.value = 'nike')
or (pp.property = 'model' and pp.value = 'xl')
PS:你觉得你这个数据表的结构设计的合理吗?我怎么感觉看着很别扭。如果数据量大的话,对于多个product有可能property和value会大量重复,这会造成大量的冗余数据。对于property不多的话(实际的情况一般也不会太多),可以考虑将每个property作为列,如下:
ProductProperties{id, product_id, brand, model}
或者对于property=value这样的键值对比较有限的话,可以考虑索性单独出来一个数据量有限的产品属性表,然后产品表做关联:
ProductProperties{id, brand, model}
Products{id, name, propertyIdList}
PS之PS:这种可变的属性列,不正是NOSQL数据库的用武之地吗,mongodb正好可以大显身手哎!
正文完