我正在尝试编写一个查询来查找部分字符串,但按与字符串前面的接近程度排序。它适用于预输入应用程序。
这是我当前的查询:
SELECT DISTINCT ON (full_name) full_name
FROM users
WHERE (lower(full_name) LIKE 'q%' OR lower(full_name) LIKE '%q%')
LIMIT 10
Run Code Online (Sandbox Code Playgroud)
但它似乎并没有按照我期望的方式排序。
因此,如果我搜索“宠物”,我想返回peter smith和petra glif之前abigail peters。
where子句可以这样写吗?目前我们没有在数据库中安装任何模糊文本搜索模块,因此我希望尽可能避免这样做。
您可以使用position(string in string)函数来实现此目的:
order by position(lower('pet') in lower(full_name))
Run Code Online (Sandbox Code Playgroud)
http://www.postgresql.org/docs/9.1/static/functions-string.html