场景是我使用like运算符实现了搜索查询:
.. WHERE caption LIKE 'hello%' OR text LIKE '%hello'
OR caption LIKE 'jame%' OR text LIKE 'jame%'
,表格类似于:
id | caption | text
---------------------
1 | Hi | Hi Jame
2 | Hello | Hello firend
3 | Jame | Hello jame
所以我希望结果集的顺序如下:
id | caption | text
---------------------
3 | Jame | Hello jame
1 | Hi | Hi Jame
2 | Hello | Hello firend
因为第3行与WHERE
和LIKE
子句的匹配更多。
有办法吗?
答案 0 :(得分:1)
SELECT *
FROM ( SELECT *,
CASE
WHEN caption LIKE 'hello%' OR text LIKE '%hello'
THEN 1
WHEN caption LIKE 'jame%' OR text LIKE 'jame%'
THEN 2
ELSE 0
END AS weight
FROM your_table
)
q
WHERE q.weight > 0
ORDER BY q.weight
答案 1 :(得分:0)
试试这个
WHERE caption LIKE 'hello%' OR text LIKE '%hello'
OR caption LIKE 'jame' OR text LIKE 'jame'
ORDER BY caption DESC
或更容易
WHERE caption LIKE 'hello'
OR caption LIKE 'jame'
ORDER BY caption DESC