Select 行按关键字分组但对每组加权而不是使用 COUNT()
Select rows grouped by keyword but weight each group instead of using COUNT()
我使用 MySQL 数据库服务器,我有一个名为 keywords
的 table,其结构如下:
kewyord_name | product_id
以及关键字列表。我可以使用以下查询根据列表对 keywords
table 进行排序:
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(*) 增加了一个以上?
如果您将列 'weight' 添加到关键字 table,您可以使用 Sum(Weight) 和 Having Sum(Weight) 而不是 Count(*)...
编辑:
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
使用 COUNT(*) 函数,每行只能递增 1。如果您希望对关键字进行不同的处理,可以将 SUM() 函数与 case 块一起使用。
例如,假设您有关键字 This
、that
、these
。如果您希望关键字 this
和 that
的权重为 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 示例。
要匹配您已有的查询设计,您只需添加 having 和 order by 子句:
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;
我使用 MySQL 数据库服务器,我有一个名为 keywords
的 table,其结构如下:
kewyord_name | product_id
以及关键字列表。我可以使用以下查询根据列表对 keywords
table 进行排序:
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(*) 增加了一个以上?
如果您将列 'weight' 添加到关键字 table,您可以使用 Sum(Weight) 和 Having Sum(Weight) 而不是 Count(*)...
编辑:
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
使用 COUNT(*) 函数,每行只能递增 1。如果您希望对关键字进行不同的处理,可以将 SUM() 函数与 case 块一起使用。
例如,假设您有关键字 This
、that
、these
。如果您希望关键字 this
和 that
的权重为 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 示例。
要匹配您已有的查询设计,您只需添加 having 和 order by 子句:
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;