选择按关键字分组的行,但对每个组进行加权,而不是使用COUNT()

时间:2015-01-22 14:47:22

标签: mysql sql select count

我使用MySQL数据库服务器,我有一个名为keywords的表,其结构如下:

kewyord_name | product_id

以及关键字列表。我可以使用以下查询基于列表对keywords表进行排序:

SELECT *, COUNT(*) 
FROM keywords 
WHERE keyword_name IN (comma separated list of keywords) 
GROUP BY product_id 
HAVING COUNT(*) > 2 
ORDER BY COUNT(*) DESC

有没有办法为关键字增加权重,即对于某些关键字,COUNT(*)会增加多个?

2 个答案:

答案 0 :(得分:1)

如果你添加一个列'重量'在关键字表中,您可以使用总和(权重)和总和(权重)而不是计数(*)...

编辑:

select productid, Sum(weights.weight)
from Keywords
Join (Select 'keyword1' as keyword, 2 as weight
      Union All
      Select 'keyword2' , 5 
      Union All
      Select 'keyword3',  6
) as weights
on Keywords.keyword_name = weights.keyword
group by productid
having Sum(weights.weight) > somevalue
order by weights.weight desc

答案 1 :(得分:1)

使用COUNT(*)函数,每行只能增加1。如果希望对关键字进行不同的处理,可以将SUM()函数与case块一起使用。

例如,我们假设您有关键字Thisthatthese。如果您希望关键字thisthat的权重为3,these权重为2,其他任何权重为1,则可以执行以下操作:

SELECT keyword_name, 
  SUM(CASE WHEN keyword_name IN ('this', 'that') THEN 3
      WHEN keyword_name IN ('these') THEN 2
      ELSE 1 END) AS weight
FROM myTable
GROUP BY keyword_name;

以下是SQL Fiddle示例。

为了匹配您已经查询的设计,您只需要添加您的拥有和订购条款:

SELECT keyword_name, 
  SUM(CASE WHEN keyword_name IN ('this', 'that') THEN 3
      WHEN keyword_name IN ('these') THEN 2
      ELSE 1 END) AS weight
FROM myTable
GROUP BY keyword_name
HAVING weight > 2
ORDER BY weight DESC;