我有一个名为 clothes_properties 的表,其中一些行如下所示:
id product_id property_name property
55 189000 color blue
56 189000 type tshirt
57 189000 size medium
58 189001 color red
59 189001 type tshirt
60 189001 size medium
我想创建一个 SQL 查询,能够从用户搜索的内容中选择正确的 product_id。因此,如果用户搜索 tshirt 和 medium,我希望 SQL 查询返回:189000 & 189001。如果用户搜索 tshirt 和 blue,我只希望返回此产品 ID:189000。如何创建 SQL 查询是这样做的吗?
最佳答案
这种表通常称为键/值存储。这是处理可扩展属性列表的有效方法,但使用起来可能有点麻烦。
像这样的查询将为您提供 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
的 View ,以使这更容易一些。
关于php - MySQL,SQL查询多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39247321/