我可以在 MySQL 中获取 json 列的 unique/distinct 值吗?

Can I get unique/distinct values of json column in MySQL?

有点难解释所以我会举例说明,

假设我有这样的 table(标签是 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]            |
+----+-------------------+--------------------+

当我想获得职业的唯一值时,我只是这样查询。

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

result
+-------------------+
|    occupation     |
+-------------------+
| Mold Maker        |
| Software Engineer |
| Electrician       |
+-------------------+

我希望标签的唯一值如下所示

+-----------+
|   tags    |
+-----------+
| Men       |
| Shop      |
| Shoes     |
| Lifestyle |
+-----------+

到目前为止,我尝试阅读 MySQL 手册和 google 中的所有 JSON_* 函数和 JSON_TABLE,但找不到方法,是否有得到我想要的结果。

您可以在 MySQL 8+:

中使用 JSON_TABLE()
select DISTINCT tag.tag
from t cross join
     json_table(t.tags, '$[*]' COLUMNS (tag varchar(255) path '$')) tag

Here 是一个 db<>fiddle.

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

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

在早期版本中,解决方案是使用数字 table。这假设您事先知道 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

Demo on DB Fiddle

| tag       |
| :-------- |
| Lifestyle |
| Men       |
| Shoes     |
| Shop      |