如何按相关性对mysql搜索结果进行排序?
我有一个与此问题类似的查询
MySQL - 如何 ORDER BY关联? INNODB Table
不同的是,这里我想从 5 个字段中搜索
add1, add2, add3, post_town, post_code
并且只有 post_code 字段中的记录不会被搜索EMPTY,其他字段记录在某些地方可能为空。如果我搜索关键字 kingston,它会返回
Acre Road, Kingston upon Thames, KT2 6EA
Kingston Road, Epsom, KT19 0DG
Kingston Road, Epsom, KT20 0DH
,这些结果是所有字段 add1、add2、add3、post_town、post_code 的组合,
我需要按以下顺序获得此结果
Kingston Road, Epsom, KT19 0DG
Kingston Road, Epsom, KT20 0DH
Acre Road, Kingston upon Thames, KT2 6EA
我当前的 SQL查询是这样的
SELECT add1, add2, add3, post_town, post_code FROM address_mst
WHERE add1 LIKE '%".$keyword."%'
OR add2 LIKE '%".$keyword."%'
OR add3 LIKE '%".$keyword."%'
OR post_town LIKE '%".$keyword."%'
OR post_code LIKE '%".$keyword."%'
所以我需要以搜索关键字开头的记录会先出现。我该怎么做?
I have a similar query as asked on this question
MySQL - How to ORDER BY RELEVANCE? INNODB Table
Difference is, here I want to search from 5 fields as
add1, add2, add3, post_town, post_code
And only records in post_code field will be NOT EMPTY, other fields records may be empty at some places. If I search for keyword kingston, it returns
Acre Road, Kingston upon Thames, KT2 6EA
Kingston Road, Epsom, KT19 0DG
Kingston Road, Epsom, KT20 0DH
and these results are combination of all fields add1, add2, add3, post_town, post_code
I need this result in following order
Kingston Road, Epsom, KT19 0DG
Kingston Road, Epsom, KT20 0DH
Acre Road, Kingston upon Thames, KT2 6EA
My Current SQL query is like this
SELECT add1, add2, add3, post_town, post_code FROM address_mst
WHERE add1 LIKE '%".$keyword."%'
OR add2 LIKE '%".$keyword."%'
OR add3 LIKE '%".$keyword."%'
OR post_town LIKE '%".$keyword."%'
OR post_code LIKE '%".$keyword."%'
So I need records with search Keyword coming in the beginning would come first. How can I do that ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不是最漂亮的,但应该有用!
Not the prettiest but should work!
对于基于相关性的排序,全文搜索更有效可靠的选择。
全文搜索
使用基于搜索术语出现次数的相关性,稍后可以使用该相关性对返回的结果进行排序。For relevancy based sorting, FULL TEXT SEARCH is the more reliable option.
FULL TEXT SEARCH
used relevancy based on the number of occurrences of the searched term which could be later on used to ORDER results returned.为什么不通过查询选择最小的合格结果,并在脚本中使用自己的逻辑为您的结果提供预先排名权重并相应地对它们进行排序?
这将帮助您:
拥有更复杂的排名标准,在查询中可能实现也可能不可能。
如果您的排名标准发生变化,则不编辑 sql 查询。
Why not select the minimal qualifying results with query, and use own logic in the script to give advance ranking weightage to your result and sort them accordingly ?
That would help you to :
Have more complex ranking criteria which may or may not be possible in the query.
Not editing the sql query if your ranking criteria changes.