我有一个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
更多例子: 所以,如果数据库中有2个字符串。
一个是
"one two three"
,另一个是
"three two one"
如果没有“一二三”,我希望先选择“一二三”,然后再选“三二”;
答案 0 :(得分:2)
您可以在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;