Mysql从多值字段中获取唯一值

时间:2013-12-22 17:23:44

标签: mysql sql

我有一个具有以下结构的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查询

获取所有唯一类别名称的列表

1 个答案:

答案 0 :(得分: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的表格,其中一行包含一个项目和一个类别。