12

I need a SQLite query that searches 1 field only using LIKE.

Basic example:

SELECT name FROM table WHERE name LIKE "%John%" ORDER BY name LIMIT 10;

The problem is that I want the result to be ordered in this way:

  1. If the field is equal (e.g. "John")
  2. If the field starts with "John" (e.g. "John Doe")
  3. If the field contains "John" (e.g. "Jane John Doe")

The following query achieves the expected result, but is slow:

SELECT name FROM table WHERE name LIKE "%John%" ORDER BY CASE WHEN name = "John" 
THEN 1 ELSE 2 END, CASE WHEN name LIKE "John%" THEN 1 ELSE 2 END, name LIMIT 10;

The query above is slower (or I tested it incorrectly) than the alternative of using 3 separate queries (one for exact match, one for starts with and one for contains).

Are there any other alternatives?

4

2 に答える 2

18

この方法で試してください:

SELECT name 
FROM table 
WHERE name LIKE "%John%" 
ORDER BY (CASE WHEN name = "John" THEN 1 WHEN name LIKE "John%" THEN 2 ELSE 3 END),name LIMIT 10 ;
于 2012-04-09T08:05:36.870 に答える
8

同等性テストで注文するだけで十分です。

ORDER BY name = "John" DESC, name LIKE "John%" DESC

ORDER BY 句は左から右に評価されます。

于 2012-04-09T08:06:46.870 に答える