全部或部分字符串 - 用于搜索功能

时间:2017-02-09 10:11:02

标签: php mysql

示例:

$test = 'My name is'

我需要返回包含以下内容的记录:'我的名字是'或者我的'或者' name'或者'是'。

我非常确定MySQL为这类任务提供了一些功能或一些正则表达式。

3 个答案:

答案 0 :(得分:1)

您需要详细了解pattern matching in Mysql

例如

SELECT * FROMwhere title REGEXP "some regex pattern"

对于你的情况,它可能是这样的事情:

SELECT * FROM `table` where title REGEXP "(My|name|is)"

答案 1 :(得分:1)

你也可以在InnoDB中使用FULLTEXT搜索:

SELECT * FROM search
WHERE MATCH(mytext) AGAINST('my name sample' IN BOOLEAN MODE);

注意

您必须在my.cnf中设置 ft_min_word_len 。默认设置为4

来自FULLTEXT搜索的说明是:https://mariadb.com/kb/en/mariadb/fulltext-index-overview/

创建示例表

CREATE TABLE `search` (
  `id` INT(10) UNSIGNED NOT NULL,
  `mytext` TEXT,
  PRIMARY KEY (`id`),
  FULLTEXT KEY `ft_mytext` (`mytext`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;

显示全部并搜索

mysql> select * from search;
+----+-----------------------------------------------------+
| id | mytext                                              |
+----+-----------------------------------------------------+
|  0 | Sample text includes My name is and much more text  |
|  1 | Only name in it                                     |
|  2 | now is includet sample                              |
|  3 | nothing of them in string                           |
+----+-----------------------------------------------------+
4 rows in set (0,00 sec)

mysql> SELECT * FROM search
    -> WHERE MATCH(mytext) AGAINST('my name sample' IN BOOLEAN MODE);
+----+-----------------------------------------------------+
| id | mytext                                              |
+----+-----------------------------------------------------+
|  0 | Sample text includes My name is and much more text  |
|  1 | Only name in it                                     |
|  2 | now is includet sample                              |
+----+-----------------------------------------------------+
3 rows in set (0,00 sec)

mysql> SELECT * FROM search WHERE MATCH(mytext) AGAINST('sample nothing' IN BOOLEAN MODE);
+----+-----------------------------------------------------+
| id | mytext                                              |
+----+-----------------------------------------------------+
|  3 | nothing of them in string                           |
|  0 | Sample text includes My name is and much more text  |
|  2 | now is includet sample                              |
+----+-----------------------------------------------------+
3 rows in set (0,00 sec)

mysql>

答案 2 :(得分:0)

使用查询如下:

select * from tbl_name where name like '%my%' OR name like '%name%' OR name like '%is%';