如何根據關鍵字匹配度排序


最近項目遇到根據關鍵字匹配度排序,要求關鍵字匹配相等排在第一,關鍵字匹配最左邊排第二,關鍵字匹配最右邊排第三,關鍵字匹配中間排最后;遇到這樣查詢排序場景,用MySQL如何實現?用搜索引擎Elasticsearch如何實現?

方法一:按照上面需求用聯合查詢,可以實現方案,但是當數據量很大時,聯合查詢效率並不太好,不是最佳方案

select id,name from
(
select id,name from title where name like '海闊天空%' ORDER BY name asc
) as c1
UNION
select id,name from
(select id,name from title where name like '%海闊天空' ORDER BY name asc
) as c2
UNION
select id,name from
(select id,name from title where name like '%海闊天空%' ORDER BY name asc
) as c3
LIMIT 0, 10;

 

 

 

方法二: 部分實現方案,查詢效率比聯合查詢稍微好些。

select id,name from channel where name like '%海闊天空%' order by replace(name, '海闊天空','') asc limit 0,10;

 

 

方法三:用搜索引擎Elasticsearch match方法,是最佳方案。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM