假设我有两列,关键字和内容。我对两者都有全文索引。我希望关键字中带有foo的行比内容中带有foo的行更具相关性。我该怎么做才能使MySQL对关键字中的匹配项进行加权,使其比内容中的匹配项高?
我正在使用“匹配条件”语法。
解:
能够通过以下方式进行这项工作:
SELECT *, CASE when Keywords like '%watermelon%' then 1 else 0 END as keywordmatch, CASE when Content like '%watermelon%' then 1 else 0 END as contentmatch, MATCH (Title, Keywords, Content) AGAINST ('watermelon') AS relevance FROM about_data WHERE MATCH(Title, Keywords, Content) AGAINST ('watermelon' IN BOOLEAN MODE) HAVING relevance > 0 ORDER by keywordmatch desc, contentmatch desc, relevance desc
实际上,使用case语句制作一对标记可能是一个更好的解决方案:
select ... , case when keyword like '%' + @input + '%' then 1 else 0 end as keywordmatch , case when content like '%' + @input + '%' then 1 else 0 end as contentmatch -- or whatever check you use for the matching from ... and here the rest of your usual matching query ... order by keywordmatch desc, contentmatch desc
同样,这仅在所有关键字匹配项的排名高于所有仅内容匹配项的情况下。我还假设关键字和内容的匹配都最高。