2015-12-02 41 views
0

我試圖在mysql中使用LIKE運算符來計算pics_indiapics_othermySQL LIKE管道上的查詢

我有一個關鍵詞管道(pics_india,pics_other,pics_other_france)即

pics_other_france 
pics_other 
pics_other|pics_other_france|pics_other|pics_other_france 
pics_other_france|pics_other_france 
pics_other_france|pics_india|pics_india|pics_other_france|pics_india 

我的查詢是這樣的:

if(medmas.mf_mm_keywords LIKE '%pics_india%','1','0')AS Pics_Ind, 
if(medmas.mf_mm_keywords LIKE '%|pics_other' OR 'pics_other|%' OR '%pics_other%' OR '%|pics_other_france' OR 'pics_other_france|%' OR '%pics_other_france%','1','0')AS Pics_Other 

如果pics_other_france | pics_india或| pics_india | pics_other_france的情況下,我想只能撥打pics_india,另外pics_other計數也是錯誤的。

回答

0

解決您的問題的最佳方法是規範化您的表(而不是在單個字段中存儲列表,您應該存儲多行)。如果你不能改變你的數據庫結構,你可以使用FIND_IN_SET函數。

首先您必須更換|用逗號,你可以使用REPLACE功能,那麼你可以撥打FIND_IN_SET:

FIND_IN_SET('pics_india', REPLACE(mf_mm_keywords, '|', ',')) 

查詢則可能是這樣的:

SELECT 
    if(FIND_IN_SET('pics_india', REPLACE(medmas.mf_mm_keywords,'|',','))>0, '1', '0') AS Pics_Ind, 
    if(
    (FIND_IN_SET('pics_other', REPLACE(medmas.mf_mm_keywords,'|',','))>0 
    OR 
    FIND_IN_SET('pics_france', REPLACE(medmas.mf_mm_keywords,'|',','))>0), 
    '1', '0') AS Pics_Ind, 
FROM ... 
WHERE ... 
+0

感謝fthiella..I試圖如你所說,現在的我Pics_ind&Pics_other的計數都是零。 –