这种表通常称为键/值存储。这是处理可扩展属性列表的有效方法,但使用起来可能有点麻烦。
这样的查询将为您提供product_id 值,按照它们与您的条件列表的匹配程度排列,最佳匹配优先。 (http://sqlfiddle.com/#!9/7870b5/2/0)
select count(*) matches, product_id
from prop
where property in ('tshirt','medium')
group by product_id
order by 1 desc
不过,此查询不知道大小、颜色和类型之间的区别。
如果您想精确匹配尺寸、颜色等,它会变得有点复杂。您需要从一个查询您的键/值属性表开始——将行转换为列。 (http://sqlfiddle.com/#!9/7870b5/3/0)
select id.product_id,
color.property color,
type.property type,
size.property size
from (select distinct product_id from prop) id
left join prop color on id.product_id = color.product_id and color.property_name = 'color'
left join prop type on id.product_id = type.product_id and type.property_name = 'type'
left join prop size on id.product_id = size.product_id and size.property_name = 'size'
然后您需要将其视为虚拟表并对其进行查询,可能是这样。 (http://sqlfiddle.com/#!9/7870b5/4/0)
select *
from (
select id.product_id,
color.property color,
type.property type,
size.property size
from (select distinct product_id from prop) id
left join prop color on id.product_id = color.product_id and color.property_name = 'color'
left join prop type on id.product_id = type.product_id and type.property_name = 'type'
left join prop size on id.product_id = size.product_id and size.property_name = 'size'
) allprops
where size='medium' and color = 'blue'
许多开发人员和 dbas 会创建一个类似于 allprops 的视图,以简化此操作。