2011-01-14 98 views
9

我有單詞列表。可以說他們是'蘋果','橙色'和'梨'。我在這樣的數據庫中的行:MySQL:列包含單詞列表

------------------------------------------------ 
|author_id | content      | 
------------------------------------------------ 
| 54   | I ate an apple for breakfast. | 
| 63   | Going to the store.    | 
| 12   | Should I wear the orange shirt? | 
------------------------------------------------ 

我正在尋找在一個InnoDB表,將返回第1和第3行查詢,因爲content列包含從我的列表中的一個或多個單詞。我知道我可以爲列表中的每個單詞查詢一次表,並使用LIKE和%通配符,但是我想知道是否有一種查詢方法用於這樣的事情?

回答

14

編輯:

事情是這樣的:

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; 

Output:

SELECT FROM yourtable WHERE content LIKE "%apple%" OR content LIKE "%orange%" 
+2

呃,我顯然晚了而你的是更全面的,所以我想你會得到一個+1。 – cbrandolino 2011-01-14 07:12:08

+0

這就是我現在正在做的,我希望避免它。雖然它避免了單獨查詢的網絡開銷,但我會假定MySQL在內部運行,在表中的每一行上運行每個單詞,這實質上是幾個查詢。我希望MySQL對這種類型的查詢有一個優化的功能。 – mellowsoon 2011-01-14 08:40:06