0

场景是我使用 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 行有更多的WHERELIKE子句匹配。

有没有办法做到这一点 ?

4

2 回答 2

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
于 2013-01-15T09:19:51.363 回答
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 
于 2013-01-15T10:17:41.347 回答