【问题标题】:Select and order by most matches按大多数匹配选择和排序
【发布时间】:2013-01-23 10:47:01
【问题描述】:

假设我分解了一个在搜索中传递的字符串。示例:“如果有狗” “如果有狗”(愚蠢的美国人)。

我们基于“”爆炸所以结果...

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,则行 45 应该显示在结果的顶部)。

这将是一个原始的“搜索相关性”逻辑。在 SQL 中是否有专门用于这种检索的术语?

建议?

【问题讨论】:

  • "如果有条狗" ;)
  • 看到之后我只需要重新启动。从来不知道我有来自小学的内存泄漏。

标签: php sql sql-server


【解决方案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

祝你好运!

【讨论】:

    【解决方案2】:

    只需将比较放在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
    

    【讨论】:

    • 如何调整它以计算与数组的匹配:t.title ~~* any(array['%string1%', '%string2%'])
    • @JamesJoshuaStreet 。 . .新问题应作为问题而非评论提出。
    猜你喜欢
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 2011-08-04
    • 2014-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-23
    相关资源
    最近更新 更多