管道上的mySQL LIKE查询

时间:2015-12-02 11:04:11

标签: mysql sql pipe delimited

我试图使用LIKE运算符计算mysql中 pics_india pics_other 的计数。

我有一个关键词管道(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 计数也是错。

1 个答案:

答案 0 :(得分: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 ...