简体   繁体   English

MySQL从多值字段获取唯一值

[英]Mysql Get Unique Values from multi value field

I have got a MySQL table with following structure 我有一个具有以下结构的MySQL表

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 我需要通过SQL查询获取所有唯一类别名称的列表

Let's assume you have a maximum of 10 categories. 假设您最多有10个类别。 You can get the list using substring_index() . 您可以使用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 . 如果列表较长,只需将更多值添加到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. 复杂的replace()假设您实际上并不想要双引号和方括号,并且实际上并不需要区分它们。

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. 您应该有一个用于item_categories的表, item_categories有一个项目行和一个类别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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