56

I have a table that contains words and an input field to search that table using a live search. Currently, I use the following query to search the table:

SELECT word FROM words WHERE word LIKE '%searchstring%' ORDER BY word ASC

Is there a way to order the results so that the ones where the string is found at the beginning of the word come first and those where the string appears later in the word come last?

An example: searching for 'hab' currently returns

  1. a lphabet
  2. h abit
  3. r ehab

but I'd like it this way:

  1. hab it (first because 'hab' is the beginning)
  2. alp hab et (second because 'hab' is in the middle of the word)
  3. re hab (last because 'hab' is at the end of the word)

or at least this way:

  1. hab it (first because 'hab' is the beginning)
  2. re hab (second because 'hab' starts at the third letter)
  3. alp hab et (last because 'hab' starts latest, at the fourth letter)

Would be great if anyone could help me out with this!

4

4 に答える 4

104

最初の方法 (単語の開始、単語の途中、単語の終了) を行うには、次のようにします。

SELECT word
FROM words
WHERE word LIKE '%searchstring%'
ORDER BY
  CASE
    WHEN word LIKE 'searchstring%' THEN 1
    WHEN word LIKE '%searchstring' THEN 3
    ELSE 2
  END

2 番目の方法 (一致した文字列の位置) を行うには、次のLOCATE関数を使用します。

SELECT word
FROM words
WHERE word LIKE '%searchstring%'
ORDER BY LOCATE('searchstring', word)

また、複数の単語が で始まる場合などに、タイ ブレーカーが必要になる場合もありhabます。そのためには、次のことをお勧めします。

SELECT word
FROM words
WHERE word LIKE '%searchstring%'
ORDER BY <whatever>, word

で始まる単語が複数ある場合は、 で始まるhab単語habがグループ化され、アルファベット順に並べ替えられます。

于 2013-09-10T18:15:04.293 に答える
25

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

SELECT word 
FROM words 
WHERE word LIKE '%searchstring%' 
ORDER BY CASE WHEN word = 'searchstring' THEN 0  
              WHEN word LIKE 'searchstring%' THEN 1  
              WHEN word LIKE '%searchstring%' THEN 2  
              WHEN word LIKE '%searchstring' THEN 3  
              ELSE 4
         END, word ASC
于 2013-09-10T18:06:08.273 に答える
11

関数を使用してINSTR、単語内の検索文字列の開始位置を返すことができます。

 ORDER BY INSTR(word,searchstring)

検索文字列が 2 つの異なる単語の同じ位置に表示される場合に、結果セットをより確定的にするには、2 つ目の式を ORDER BY に追加します。

 ORDER BY INSTR(word,searchstring), word

(たとえば、検索文字列はとhabの両方の 2 番目の位置に表示されます)chablisshabby

于 2013-09-10T18:20:14.837 に答える