最近项目遇到根据关键字匹配度排序,要求关键字匹配相等排在第一,关键字匹配最左边排第二,关键字匹配最右边排第三,关键字匹配中间排最后;遇到这样查询排序场景,用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方法,是最佳方案。