MySQL:列包含单词列表中的单词

mel*_*oon 15 mysql sql innodb

我有一个单词列表.让我们说它们是'Apple','Orange'和'Pear'.我在数据库中有这样的行:

------------------------------------------------
|author_id   |  content                        |
------------------------------------------------
| 54         | I ate an apple for breakfast.   |
| 63         | Going to the store.             |
| 12         | Should I wear the orange shirt? |
------------------------------------------------
Run Code Online (Sandbox Code Playgroud)

我正在寻找一个返回第1行和第3行的InnoDB表的查询,因为该content列包含我列表中的一个或多个单词.我知道我可以为列表中的每个单词查询一次表,并使用LIKE和%通配符,但我想知道是否有一个查询方法可用于这样的事情?

Joh*_* K. 29

MySQL(我相信5.0版本)增加了在SQL中使用正则表达式的能力.

查看:http: //www.brainbell.com/tutorials/MySQL/Using_MySQL_Regular_Expressions.htm

SELECT author_id, content
FROM AuthorTableName
WHERE content REGEXP 'Apple|Orange|Pear'
ORDER BY author_id;
Run Code Online (Sandbox Code Playgroud)

  • 使用REGEXP'Apple。* Orange。* Pear'将产生包含指定顺序中所有单词的结果。 (3认同)

Nav*_*eed 19

编辑:

像这样的东西:

SELECT * FROM yourtable WHERE content LIKE '%apple%' OR content LIKE '%orange%'
Run Code Online (Sandbox Code Playgroud)

您可以循环您的单词以创建WHERE子句条件.

例如:

$words = array( 'apple', 'orange' );
$whereClause = '';
foreach( $words as $word) {
   $whereClause .= ' content LIKE "%' . $word . '%" OR';
}

// Remove last 'OR'
$whereClause = substr($whereClause, 0, -2);

$sql = 'SELECT * FROM yourtable WHERE' . $whereClause;

echo $sql;
Run Code Online (Sandbox Code Playgroud)

输出:

SELECT * FROM yourtable WHERE content LIKE "%apple%" OR content LIKE "%orange%" 
Run Code Online (Sandbox Code Playgroud)

  • 呃,我显然已经迟到了,你的更完整,所以我想你会得到+1. (2认同)