这个有点难解释,所以我会举个例子来解释,
假设我有这样的表(标签是 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
| tag | | :-------- | | Lifestyle | | Men | | Shoes | | Shop |
关于mysql - 我可以在 MySQL 中获取 json 列的唯一/不同值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58788241/