在select语句中确定字符串的优先级


Prioritizing strings in a select statement

我有一个select语句,如果字符串包含下面的任何单词,它将选择它,但它不会按照单词包含的顺序选择它。例如,如果数据库中的字符串是"三二一",而不是"一二三",它还是会选择它。我想让它先按照字符串的顺序排列优先级,然后再尝试得到那些不是按这个顺序排列的。这可能吗?

$text1 = "one";
$text2 = "two";
$text3 = "three";
SELECT text,
((text LIKE '%$text1%') + (text LIKE '%$text2%') + (text LIKE '%$text3%')) as `matches` 
FROM tableName 
HAVING `matches` > 0
ORDER BY `matches` DESC, rand() LIMIT 1

更多的例子:如果数据库中有两个字符串

"one two three" 

,另一个

"three two one"

如果没有"一二三",我希望先选择"一二三",然后再选择"三二一";

可以在order by:

中指定优先级。
SELECT text,
       ((text LIKE '%$text1%') + (text LIKE '%$text2%') + (text LIKE '%$text3%')) as `matches` 
FROM tableName 
HAVING `matches` > 0
ORDER BY `matches` DESC, 
         (case when text like '%$text1%$text2%text3%' then 1
               when text like '%$text3%$text2%text1%' then 2
               . . .
          else 999 end),
         rand()
LIMIT 1;