我有一个 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"
我想先选有“一二三”的,如果没有“一二三”,再选“三二一”;
最佳答案
您可以在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;
关于php - 在 select 语句中确定字符串的优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32597231/