我可以在 MySQL 中获取 json 列的唯一/不同值吗?

Kya*_*Soe 3 mysql sql arrays json unnest

解释起来有点困难,所以我会举个例子来解释,

假设我有这样的表(标签是 json 列)

+----+-------------------+--------------------+
| id |    occupation     |        tags        |
+----+-------------------+--------------------+
|  1 | Mold Maker        | [Men, Shop, Shoes] |
|  2 | Software Engineer | [Men, Lifestyle]   |
|  3 | Electrician       | [Shop, Lifestyle]  |
|  4 | Software Engineer | [Men, Lifestyle]   |
|  5 | Software Engineer | [Shoes]            |
+----+-------------------+--------------------+
Run Code Online (Sandbox Code Playgroud)

当我想获得职业的独特价值时,我只需这样查询即可。

SELECT DISTINCT occupation FROM customers;
或者
SELECT occupation FROM customers GROUP BY occupation;

result
+-------------------+
|    occupation     |
+-------------------+
| Mold Maker        |
| Software Engineer |
| Electrician       |
+-------------------+
Run Code Online (Sandbox Code Playgroud)

我想要按行标记的唯一值,如下所示

+-----------+
|   tags    |
+-----------+
| Men       |
| Shop      |
| Shoes     |
| Lifestyle |
+-----------+
Run Code Online (Sandbox Code Playgroud)

到目前为止,我尝试阅读 MySQL 手册和谷歌中的所有 JSON_* 函数和 JSON_TABLE,但找不到方法来做到这一点,无论如何都可以得到我想要的结果。

GMB*_*GMB 5

在 MySQL 8.0 中,json 函数json_table()可以方便地完成此任务:

select distinct tag
from 
    mytable,
    json_table(
        tags,
        "$[*]"
        columns (tag varchar(50) PATH "$")
    ) t
order by tag
Run Code Online (Sandbox Code Playgroud)

在早期版本中,解决方案是使用数字表。假设您事先知道 json 数组中元素的最大数量:

select distinct replace(
    json_extract(tags, concat('$[', nums.n, ']')),
    '"',
    ''
) tag
from 
    (
        select 0 n 
        union all select 1 
        union all select 2 
        union all select 3 
        union all select 4
    ) nums
    inner join mytable t
        on json_extract(t.tags, concat('$[', nums.n, ']')) is not null 
    order by tag
Run Code Online (Sandbox Code Playgroud)

DB Fiddle 上的演示

| 标签|
| :-------- |
| 生活方式 |
| 男士 |
| 鞋子 |
| 店铺 |