简体   繁体   中英

Mysql Get Unique Values from multi value field

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM