Reputation: 4835
I have got a MySQL table with following structure
id categories
1 ["Pizza","Subs","Sandwiches","Seafood","Italian"]
2 ["Pizza","Salad","Sandwiches","Subs"]
3 ["Fast Food","Burgers","Salad","American","Cafe"]
4 ["Coffee","Cafe"]
I need to get list of all unique category names via SQL query
Upvotes: 1
Views: 210
Reputation: 1269493
Let's assume you have a maximum of 10 categories. You can get the list using 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;
If you have a longer list, just add more values to the subquery for n
. The complex replace()
assumes that you don't actually want the double quotes and square brackets and that they are not really needed to distinguish among the categories.
As noted in the comments, this is a very bad data structure. You should have a table for item_categories
with one row for an item and a single category.
Upvotes: 2