这是我的表结构-表名“propassign”

(indexed)        (composite index for attributeName and attributeValue)
 productId     attributeName     attributeValue
    1              Height             3
    1              Weight             1
    1              Class              X1
    1              Category           C1
    2              Height             2
    2              Weight             2
    2              Class              X2
    2              Category           C1
    3              Height             3
    3              Weight             1
    3              Class              X1
    3              Category           C1
    4              Height             4
    4              Weight             5
    4              Class              X2
    4              Category           C3

我要做的是,获取productid列表,按最大匹配属性值对排序。在real表中,我使用的是属性名和值的数字id,这里使用的是文本以便于表示。
所以,如果我想找到productid=1的匹配产品,我希望它寻找具有最大匹配的产品(比如height=3,weight=1,class=x1和category=c1)。可能不存在100%匹配(全部4个匹配)的匹配,但如果存在,它们应该首先出现,然后是productid,productid有任何3个匹配的属性,然后是任何2个,等等。
如果需要的话,我可以添加更多的索引,如果不需要的话更好,因为有数百万行。准确地说是Mariadb v10。
期望的结果-如果我试图找到productid=1的匹配产品,它应该以相同的顺序返回following。
productId
-----------
3
2

原因-3具有与1匹配的所有属性,2具有一些匹配项,而4没有匹配项。

最佳答案

您可以使用条件聚合首先检索具有最大匹配数的productid。

select productId,
    count(case when attributeName = 'Height' and attributeValue='3' then 1 end)
    + count(case when attributeName = 'Weight' and attributeValue='1' then 1 end)
    + count(case when attributeName = 'Category' and attributeValue='C1' then 1 end) as rank
from mytable
group by productId
order by rank desc

上面的查询返回所有行,即使匹配项为0。如果只想返回具有1个或多个匹配项的行,请使用下面的查询,该查询应该能够利用组合索引:
select productId, count(*) as rank
from mytable
where (attributeName = 'Height' and attributeValue = '3')
or (attributeName = 'Weight' and attributeValue = '1')
or (attributeName = 'Category' and attributeValue = 'C1')
group by productId
order by rank desc

关于mysql - 查找具有最大匹配属性的项目,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31489498/

10-14 15:01
查看更多