2014-10-30 45 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