我在PostgreSQL中以相同的顺序提供以下数据 -
Building Maintenance - Painting
Paint Expense
Painting Supplies
搜索结果应按以下顺序显示:
如果用户输入搜索字符串" 绘制" 结果应该像 -
Paint Expense
Painting Supplies
Building Maintenance - Painting
任何帮助都将不胜感激。
答案 0 :(得分:0)
这适用于SQL Server
,但您只需将其更改为PostrgeSQL
:
DECLARE @f VARCHAR(MAX) = 'paint'
DECLARE @t TABLE ( v VARCHAR(MAX) )
INSERT INTO @t
VALUES ( 'Building Maintenance - Painting' ),
( 'Paint Expense' ),
( 'Painting Supplies' )
SELECT * ,
CASE WHEN ( v LIKE @f + ' %'
OR v LIKE '% ' + @f
OR v LIKE '% ' + @f + ' %'
) THEN 1
WHEN v LIKE @f + '%' THEN 2
WHEN v LIKE '%' + @f + '%' THEN 3
ELSE 4
END AS ordering
FROM @t
ORDER BY ordering
输出:
v ordering
Paint Expense 1
Painting Supplies 2
Building Maintenance - Painting 3
第一种是完全匹配,例如'paint ...'
或'... paint'
或'... paint ...'
。
第二个:'paint...'
。
第三个:'...paint...'
。
您也可以直接在order
子句中执行此操作:
SELECT *
FROM @t
ORDER BY CASE WHEN ( v LIKE @f + ' %'
OR v LIKE '% ' + @f
OR v LIKE '% ' + @f + ' %'
) THEN 1
WHEN v LIKE @f + '%' THEN 2
WHEN v LIKE '%' + @f + '%' THEN 3
ELSE 4
END