如何根据MySQL中的关键词过滤数据?

时间:2017-07-13 05:41:00

标签: php mysql

我在使用过滤器关键字检索数据时遇到问题。我有这样的消息表

我的过滤表: -

+--+-------+-----------+---------+---------------+
|id|user_id|for_page_id|key_words|    message    |
+--+-------+-----------+---------+---------------+
| 1|     12|        2  |he,you   |You are awesome|
| 2|     12|        2  |the,book |this is good   |
+--+-------+-----------+---------+---------------+

我有一串关键字,我想找到该关键字的相应消息
我试过这个: -

$string='he is good';
$keyWords=explode(' ',$string);
$query="SELECT * FROM `filter` WHERE `key_words` like '".$keyWords[0]."' or`key_words` like 
        '".$keyWords[1]."' or`key_words` like '".$keyWords[2]."'";
echo ($query);

查询看起来像

SELECT * FROM `filter` WHERE `key_words` like 'he' or`key_words` like 'is' or`key_words` like 'good'

它输出为

| 1|     12|        2  |he,you   |You are awesome|
| 2|     12|        2  |the,book |this is good   |

接受的输出是

| 1|     12|        2  |he,you   |You are awesome|

任何想法都会受到赞赏。

2 个答案:

答案 0 :(得分:3)

FIND_IN_SET()函数可能就是你要找的。

SELECT FIND_IN_SET('b','a,b,c,d');
-> 2

如果在列表中找不到该字符串,则返回0.

以下是MySQL documentation

的链接

答案 1 :(得分:1)

试试这个。希望能帮到你

$string='he is good';
$keyWords=explode(' ',$string);
$searchQuery='';
foreach ($keyWords as $word) {
    $word = trim($word);
    if ($word) {
        $searchQuery = $searchQuery . "find_in_set('$word', trim(key_words)) > 0 or ";
    }
}
$searchQuery = chop($searchQuery, ' or ');
$query="SELECT * FROM filter WHERE ".$searchQuery;
echo ($query);

查询将像

SELECT * FROM filter WHERE find_in_set('he', trim(key_words)) > 0 or find_in_set('is', trim(key_words)) > 0 or find_in_set('good', trim(key_words)) > 0