MySQL:列包含单词列表中的单词
我有一张单子。让我们说它们是“苹果”、“橘子”和“梨”。我在数据库中有如下行:MySQL:列包含单词列表中的单词,sql,mysql,innodb,Sql,Mysql,Innodb,我有一张单子。让我们说它们是“苹果”、“橘子”和“梨”。我在数据库中有如下行: ------------------------------------------------ |author_id | content | ------------------------------------------------ | 54 | I ate an apple for breakfast. | | 63 |
------------------------------------------------
|author_id | content |
------------------------------------------------
| 54 | I ate an apple for breakfast. |
| 63 | Going to the store. |
| 12 | Should I wear the orange shirt? |
------------------------------------------------
SELECT * FROM yourtable WHERE content LIKE '%apple%' OR content LIKE '%orange%'
我正在寻找一个InnoDB表上的查询,该表将返回第一行和第三行,因为content
列包含我列表中的一个或多个单词。我知道我可以为列表中的每个单词查询一次表,并使用LIKE和%通配符,但我想知道是否有一种单一的查询方法用于这种事情?编辑:
$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;
大概是这样的:
------------------------------------------------
|author_id | content |
------------------------------------------------
| 54 | I ate an apple for breakfast. |
| 63 | Going to the store. |
| 12 | Should I wear the orange shirt? |
------------------------------------------------
SELECT * FROM yourtable WHERE content LIKE '%apple%' OR content LIKE '%orange%'
可以循环使用单词来创建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;
MySQL(我相信是5.0版本)增加了在SQL中使用正则表达式的能力
退房:
嗯,我显然迟到了,而你的更完整,所以我猜你会得到+1。这就是我现在正在做的,我希望避免它。虽然它确实避免了单独查询的网络开销,但我假设MySQL在内部对表中的每一行运行每个单词,这实际上是几个查询。我希望MySQL有一个针对这类查询的优化功能。非常感谢。正是我需要的。优雅,这应该是正确的答案。我想5.0是一个可以接受的最低版本。使用REGEXP“Apple.*Orange.*Pear”将生成包含指定顺序的所有单词的结果。这并不会将所有结果都放在简单的引号之间。相去甚远。你让我度过了一个夜晚,tks。