2014-03-04 32 views
0

我在查找返回mySQL數據庫中的文本字段中找到的匹配單詞列表的查詢。訣竅是文本字段包含多個我不想返回的其他單詞。mySQL返回文本字段中的單詞列表

以汽車數據庫爲例,其中「顏色」文本字段包含汽車上的所有顏色。

說我們有在「顏色」字段包含這些條目行:

"candy apple red, black" 
"reddish brown" 
"sunset red, white" 
"Purple, Cherry red, pink polkadots" 
"white" 
"sunset red" 

我可以這樣做:

SELECT colours from CARS WHERE colours REGEXP 'red' 

返回所有在它有「紅色」的地方行,但它會返回該字段中的所有內容。

訣竅是我想要的結果列表看起來像這樣:

"candy apple red" 
"reddish brown" 
"sunset red" 
"cherry red" 

目前我使用PHP來從服務器獲取完整的結果列表考慮,然後通過從列表中工作那裏。但是,如果數據庫變大,這可能會花費很多。

謝謝!

編輯:

這裏是部分答案只包括在任何「顏色」字段中發現的第一個顏色(和刪除重複),這不是太討厭查詢:

SELECT distinct 
TRIM(CONCAT(SUBSTRING_INDEX(SUBSTRING(colours, 1, LOCATE('red',colours)-1), ',' , -1), 
SUBSTRING_INDEX(SUBSTRING(colours, LOCATE('red',colours)), ',' , 1)))as found 
FROM CARS 
WHERE colours REGEXP 'red' 

理想情況下,我們可以將此擴展爲也解決了一個字段中的多個事件。例如,如果我們有這樣一個領域:「紫,櫻桃紅,粉色polkadots,夕陽紅」

+1

您不應該將事物列表存儲在字符串變量中。您應該使用關聯/聯結表。 –

+0

@戈登,真的,但不幸的是不是它完成的方式。 –

回答

1

這裏有一個方法可以做到這一點,但它是不是特別「好」:

SELECT (case when substring_index(colours, ', ', 1) like '%red%' 
      then substring_index(colours, ', ', 1) 
      when substring_index(colours, ', ', 2) like '%red%' 
      then substring_index(substring_index(colours, 2), ', ', -1) 
      when substring_index(colours, ', ', 3) like '%red%' 
      then substring_index(substring_index(colours, 3), ', ', -1) 
      when substring_index(colours, ', ', 4) like '%red%' 
      then substring_index(substring_index(colours, 4), ', ', -1) 
      . . . 
     end) 
from CARS 
WHERE colours like '%red%'; 

您需要手動將查詢擴展到數據中最長的列表。而且,這會返回第一個匹配項目,而不是全部。

+0

謝謝戈登,這給了我一些想法。我已經編輯了我的問題,以包含我迄今爲止提出的部分解決方案。基本上它找到搜索字符串,然後在它之前和之後查找逗號。 –

+0

如果你想擴展這個想法,那麼這個方法實際上更容易。您需要將每個條件分解成單獨的「case」語句。 –

相關問題