[英]Mysql Get Unique Values from multi value field
我有一個具有以下結構的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查詢獲取所有唯一類別名稱的列表
假設您最多有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
的表, item_categories
有一個項目行和一個類別。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.