I use MySQL database server and I have a table named keywords
with the following structure:
kewyord_name | product_id
As well as a list of keywords. I can sort the keywords
table based on the list with the following query:
SELECT *, COUNT(*)
FROM keywords
WHERE keyword_name IN (comma separated list of keywords)
GROUP BY product_id
HAVING COUNT(*) > 2
ORDER BY COUNT(*) DESC
Is there a way to add weight to the keywords, ie for some of the keywords the COUNT(*) to be increased with more than one?
If you add a column 'weight' to the keywords table you can use Sum(Weight) and Having Sum(Weight) instead of Count(*)...
Edit:
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
Using the COUNT(*) function you'll only be able to increment by one with each row. If you want keywords to be treated differently, you could use the SUM() function with a case block.
For example, let's say you have keywords This
, that
, these
. If you want keyword this
and that
to have a weight of 3, these
a weight of 2, and anything else a weight of 1, you can do this:
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;
Here is an SQL Fiddle example.
To match the design of your query you have already, you just need to add your having and order by clauses:
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.