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

标签 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]            |
+----+-------------------+--------------------+

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

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 手册和谷歌中的所有 JSON_* 函数和 JSON_TABLE,但找不到方法,是否有办法获得我想要的结果。

最佳答案

在 MySQL 8.0 中,json 函数 json_table() 可以派上用场:

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

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

关于mysql - 我可以在 MySQL 中获取 json 列的唯一/不同值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58788241/

相关文章:

javascript - 成功提示消息不适用于 AJAX

php - 显示特定时间点的表数据

sql - 减少 SQL Server 中的查询冗余

c++ - 这是 C++ 中带有指针的数组的良好使用/代码吗?

java - 考虑重复,在数组中存储随机值

php - MySQL - 计算查询后的行数

php - Zend 选择 NOT IN

mysql - MySQL 是否可以自动初始化日期字段?

sql - 保持唯一的字符串缩写

c++ - 大数组上的段错误