根据字符串相关性和字符串顺序在数据库中搜索字符串

时间:2015-09-16 01:29:44

标签: php mysql

我有一个SQL搜索语句的例子,我首先尝试按顺序查找字符串的一部分。所以它首先搜索完整的“一二三”字符串,然后继续“一二”,然后“二三”,最后一直到一个单词,但它从不向后搜索。只是按顺序。所以,例如,它永远不会搜索“三二一”,只搜索“一二三”,我想知道是否可以将所有这些单个查询语句组合成一个查询?谢谢。

$text1 = "one";
$text2 = "two";
$text3 = "three";

SELECT text FROM tableName WHERE text LIKE "$text1 $text2 $text3"  
SELECT text FROM tableName WHERE text LIKE "$text1 $text2"
SELECT text FROM tableName WHERE text LIKE "$text2 $text3"
SELECT text FROM tableName WHERE text LIKE "$text1" 
SELECT text FROM tableName WHERE text LIKE "$text2" 
SELECT text FROM tableName WHERE text LIKE "$text3"  

1 个答案:

答案 0 :(得分:1)

是。您可以搜索它们,然后按相关性排序。这是一种方法:

SELECT text
FROM tableName
WHERE text LIKE "$text1" OR
      text LIKE "$text2" OR
      text LIKE "$text3" 
ORDER BY (text LIKE "$text1 $text2 $text3") DESC,
         (text LIKE "$text1 $text2") DESC,
         (text LIKE "$text2 $text3") DESC,
         (text LIKE "$text1" ) DESC,
         (text LIKE "$text2" ) DESC,
         (text LIKE "$text3" ) DESC