用于检索匹配单词的SQL查询

时间:2013-06-02 11:56:55

标签: php mysql

我有一个要在DB中搜索的句子。我删除了停用词并将其拆分为变量中的关键字数组,即$ key [0],$ key [1],$ key [2]。我想按照最大匹配关键字数量的顺序检索数据,对此有何不同?

请帮忙。

现在我正在使用

SELECT * 
FROM 'table' 
WHERE ('colomn' LIKE '%$key1%' 
    AND 'colomn' LIKE '%$key2%'
    AND 'colomn' like '%$key3%'
      );

如果没有结果

SELECT * 
FROM   'table' 
WHERE ('colomn' LIKE '%$key1%' 
     OR 'colomn' LIKE '%$key2%' 
     OR 'colomn' LIKE '%$key3%'
       );

2 个答案:

答案 0 :(得分:3)

MySQL非常可爱:

SELECT *, (colomn like "%$key1%") + (colomn like "%$key2%") + (colomn like "%$key3%") as match_rate
FROM table
WHERE (colomn like "%$key1%" or colomn like "%$key2%" or colomn like "%$key3%")
ORDER BY match_rate DESC;

答案 1 :(得分:1)

不要在表名和列名周围使用单引号而是使用反引号

像那样

 Select * from `table` where (`colomn`....

而不是

 Select * from 'table' where ('colomn'........

使用带有OR的第二个查询

我认为你会找那样的东西

 order by case 
      when `colomn` LIKE "%$key1%" and `colomn` LIKE "%$key2%" and `colomn` LIKE "%$key3%" then 1 
      when (`colomn` LIKE "%$key1%" and `colomn` LIKE "%$key2%")  or (`colomn` LIKE "%$key1%" and `colomn` LIKE "%$key3%") or (`colomn` LIKE "%$key3%" and `colomn` LIKE "%$key2%") then 2 
    else 3 
 end