2014-10-30 44 views
0

我问了一个类似的问题,但它已成为一个更大的问题。MySQL在混合文本列中选择引号“”中的单词

下面的问题可以满足2个选项,但如果单个选项存储在数据库中,则不会。请参阅:使用SUBSTRING_INDEX()。通过回答Joyal George: MYSQL SELECT multiple values between "" in Column

我有一个WordPress的表格,它捕获有关想要在某些领域接收更新的人的信息。他们可以选择1个或更多区域。

然后我有一个报告插件,它只接受SQL来检索报告的数据。没有应用层,只有SQL查询到MYSQL数据库

如果有人只选择1个区域,我只需要提取该区域。如果他们选择多个区域,我需要提取用逗号分隔的每个区域。他们最多可以选择9个区域。

数据列如下:

1区:

Western Cape 

多个区域:

a:3:{i:0;s:10:"North-West";i:1;s:12:"Western Cape";i:2;s:13:"Northern Cape";} 

我使用一个case语句(以前的问题与此数据库结构)

select 
a.entry_id, 
MAX(case when field_id = 74 then entry_value end) as FirstName, 
MAX(case when field_id = 75 then entry_value end) as LastName, 
MAX(case when field_id = 76 then entry_value end) as Email, 
MAX(case when field_id = 78 then entry_value end) as Phone, 
MAX(case when field_id = 79 then 
(select concat( 
    SUBSTRING_INDEX( 
     SUBSTRING_INDEX( 
      SUBSTRING_INDEX( 
       entry_value, 
       '"', 
       4 
      ), 
      '"', 
      2 
     ), 
     '"', 
     -1 
    ), 
    ",", 
    SUBSTRING_INDEX(
     SUBSTRING_INDEX( 
      SUBSTRING_INDEX(
       entry_value, 
       '"', 
       4 
      ), 
      '"', 
      4 
     ), 
     '"', 
     -1 
    ) 
)) 
end) as InterestedIn, 
MAX(case when field_id = 81 then entry_value end) as Province from ch_arf_entry_values a GROUP BY a.entry_id 

我需要调整'as Interestrested'来迎合1个输入值。

我需要找到最后一种情况“作为省

任何援助的解决方案将不胜感激。

回答

1

你应该找到一种更好的方式来表示你想要什么,但我认为下面接近:

select concat_wc(',', substring_index(substring_index(entry_value, '"', 2), '"' -1), 
       substring_index(substring_index(entry_value, '"', 4), '"' -1), 
       . . . 
       ) 

你可能要忍受基于值的数量中的停止条件值的数量在字符串中,导致类似:

select concat_ws(',', 
       case when num_entry_values >= 1 then substring_index(substring_index(entry_value, '"', 2), '"' -1) end, 
       case when num_entry_values >= 2 then substring_index(substring_index(entry_value, '"', 4), '"' -1) end, 
       . . . 
      ) 

如果你没有这个号码,就可以通过在字符串中计数双引号的数量计算。

编辑:

要计算的条目数,算上"

from (select aev.*, 
      (length(entry_value) = length(replace(entry_value, '"', '')))/2 as num_entry_values 
     from ch_arf_entry_values aev 
    ) aev 
+0

您好,感谢答案。我没有数字num_entry_values。我如何计算这个?我使用的情况下(选择 ROUND((LENGTH(entry_value) - 长度(REPLACE(entry_value,''','')))/ LENGTH(''') )AS count FROM ch_arf_entry_values)> = 1 then .. 。但它不工作:(有没有办法在变量entry_value中选择COUNT('“')? – 2014-10-31 09:02:41