最近專案遇到根據關鍵字匹配度排序,要求關鍵字匹配相等排在第一,關鍵字匹配最左邊排第二,關鍵字匹配最右邊排第三,關鍵字匹配中間排最后;遇到這樣查詢排序場景,用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方法,是最佳方案,
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/21747.html
標籤:SQL Server
