假设我爆炸了搜索中传递的字符串。例如:“如果有狗” “如果有狗”(愚蠢的美国人)。
我们根据“”结果爆炸......
if
there
were
a
dog
现在我要运行SQL select * from table_name query where column_name like
'%something%' or column_name like '%somethingelse%'...
我正在尝试确定如何按包含最多匹配的行搜索表和排序。 (即,如果行 45 包含上述拆分项目的 4 且行 21 仅包含 2 ,则行<应该在结果的顶部显示strong> 45 。
这将是一种原始的“搜索相关性”逻辑。在SQL中是否有这种检索的特定术语?
建议?
答案 0 :(得分:5)
只需将比较放在order by
子句中,使用case
语句将它们转换为0/1,然后将它们加起来:
select *
from table_name query
where column_name like '%something%' or column_name like '%somethingelse%'
order by ((case when column_name like '%something%' then 1 else 0 end) +
(case when column_name like '%somethingelse%' then 1 else 0 end)
. . .
) desc
我倾向于将查询写成:
select (Match1+Match2+. . .) as NumMatches, <rest of columns>
from (select t.*,
(case when column_name like '%something%' then 1 else 0 end) as Match1,
. . .
from tablename
) t
order by NumMatches desc
答案 1 :(得分:1)
这是@ Gordon的优秀答案的变体:
SELECT FieldToSearch,
CASE WHEN ' ' + FieldToSearch + ' ' like '% if %' then 1 else 0 end
+ CASE WHEN ' ' + FieldToSearch + ' ' like '% there %' then 1 else 0 end
+ CASE WHEN ' ' + FieldToSearch + ' ' like '% was %' then 1 else 0 end
+ CASE WHEN ' ' + FieldToSearch + ' ' like '% a %' then 1 else 0 end
+ CASE WHEN ' ' + FieldToSearch + ' ' like '% dog %' then 1 else 0 end matches
FROM YourTable
ORDER BY matches DESC
这是Fiddle。
祝你好运!