2013-12-22 43 views
1

我有一個MySQL表結構如下mysql的獲取從多值字段中唯一值

id  categories 
1  ["Pizza","Subs","Sandwiches","Seafood","Italian"] 
2  ["Pizza","Salad","Sandwiches","Subs"] 
3  ["Fast Food","Burgers","Salad","American","Cafe"] 
4  ["Coffee","Cafe"] 

我需要通過SQL查詢來獲取所有獨特的類別名稱的列表

+0

你確實在這個領域有方括號嗎? –

+0

看到正常化 – Strawberry

+2

你可能會發現這個很有用:http://stackoverflow.com/questions/1096679/can-mysql-split-a-column –

回答

2

讓我們假設你有一個最大10個類別。您可以使用substring_index()獲取列表。

select distinct category 
from (select substring_index(substring_index(categories, ',', n.n), ',', -1) as category 
     from (select replace(replace(replace(categories, '"', ''), '[', ''), ']', '') as categories 
      from t 
     ) t cross join 
      (select 1 as n union all select 2 union all select 3 union all select 4 union all select 5 union all 
      select 6 union all select 7 union all select 8 union all select 9 union all select 10 
     ) n 
    ) c 
where category is not null; 

如果你有一個較長的列表,只需添加更多的價值的子查詢n。複雜的replace()假設你實際上不需要雙引號和方括號,並且他們不是真的需要區分這些類別。

正如評論中指出的那樣,這是一個非常糟糕的數據結構。對於item_categories,您應該有一個表格,其中一行用於一個項目和一個類別。

+0

我想你錯過了一個額外的substring_index調用我爲你編輯。在這裏證明http://sqlfiddle.com/#!2/f8d3d/3/0。很好回答btw! –

+0

非常感謝您的幫助,讓我找出結果。 –

+0

@AyazAlavi,如果你的行有可能沒有任何類別,比如'[]' –