MySQL通配符像多个单词的查询

时间:2014-10-07 17:26:42

标签: mysql

我有一个mysql查询如下。

$query="SELECT name,activity FROM appid 
where result > 5 AND name LIKE :term ORDER BY name ASC LIMIT 0,40";

$result = $pdo->prepare($query);

$result->bindvalue(':term','%'.$_GET["q"].'%',PDO::PARAM_STR);
$result->execute();

我想做的就是这个。

我有这样的条目,我想找到

'新闻&天气'

但是当我输入

'新闻天气'

它当然不会找到它。我怎样才能输入并检索该条目?

2 个答案:

答案 0 :(得分:2)

Regular expressions可以解决问题:

select *
from appid
where name rlike 'news|weather' -- Matches 'news' or 'weather'

另一个例子:

select *
from appid
where name rlike 'news.*weather' -- Matches 'news' and 'wether' 
                                 -- with any characters in-between or none at all
                                 -- (ordered)

再多一次:

select *
from appid
where name rlike '^news.{1,}weather$' -- Matches any text that starts with 'news'
                                      -- and has at least one character before
                                      -- ending with 'weather'

常规压缩可用于在文本字段上创建非常复杂的过滤器。请阅读上面的链接以获取更多信息。


如果您可以为表格添加全文索引,Full-text search可能是更好的方法。具体来说,是boolean Full-Text search

select *
from appid
where match(name) against (+news +weather)

答案 1 :(得分:0)

我认为唯一可行的方法是通过代码:

选项A:将查询参数中的空格替换为'%'在代码中,但这当然会使多个单词排序

选项B:在空格上拆分参数,并根据需要使用尽可能多的LIKE动态构建查询,添加额外的":termN"每个参数。

相关问题