[英]Get distinct values from MySQL JSON array
I got a MySQL data Table, with a JSON Column containing a list of Values:我得到了一个 MySQL 数据表,其中包含一个包含值列表的 JSON 列:
CONSTRAINT_TABLE约束表
ID | CONSTRAINT_TYPE | CONSTRAINT_VALUES
----+-----------------+--------------------------------
'2'| 'testtype' |'[801, 751, 603, 753, 803]'
...| ... | ...
What I want to have is a distinct, comma-seperated List of JSON-Values.我想要的是一个不同的、逗号分隔的 JSON 值列表。 I tried it with group_concat, but it applys to the arrays, not the single values.
我用 group_concat 尝试过,但它适用于数组,而不是单个值。
SELECT group_concat(distinct constraint_values->>'$')
FROM constraint_table c
WHERE c.constraint_type = "testtype";
Actual result:实际结果:
[801, 751, 603, 753, 803],[801, 751],[578, 66, 15],...
My target result:我的目标结果:
801, 751, 603, 753, 803, 578, 66, 15 ...
without duplicates.没有重复。 As rows would be nice, too.
因为行也不错。
Ideas, anyone?想法,有人吗?
Sorry for necromancing, but I've encountered similar issue.很抱歉进行死灵,但我遇到了类似的问题。 The solution is:
JSON_TABLE()
available since MySQL 8.0.解决方案是:
JSON_TABLE()
自 MySQL 8.0 起可用。
First, merge the arrays in rows into one-row single array.首先,将行中的数组合并为一行单个数组。
select concat('[', -- start wrapping single array with opening bracket
replace(
replace(
group_concat(vals), -- group_concat arrays from rows
']', ''), -- remove their opening brackets
'[', ''), -- remove their closing brackets
']') as json -- finish wraping single array with closing bracket
from (
select '[801, 751, 603, 753, 803]' as vals
union select '[801, 751]'
union select '[578, 66, 15]'
) as jsons;
# gives: [801, 751, 603, 753, 803, 801, 751, 578, 66, 15]
Second, use json_table
to convert the array into rows.其次,使用
json_table
将数组转换为行。
select val
from (
select concat('[',
replace(
replace(
group_concat(vals),
']', ''),
'[', ''),
']') as json
from (
select '[801, 751, 603, 753, 803]' as vals
union select '[801, 751]'
union select '[578, 66, 15]'
) as jsons
) as merged
join json_table(
merged.json,
'$[*]' columns (val int path '$')
) as jt
group by val;
# gives...
801
751
603
753
803
578
66
15
See https://dev.mysql.com/doc/refman/8.0/en/json-table-functions.html#function_json-table见https://dev.mysql.com/doc/refman/8.0/en/json-table-functions.html#function_json-table
Notice group by val
for getting distinct values.注意
group by val
以获得不同的值。 You can also order
them and everything...你也可以
order
它们和所有东西......
Or you can use group_concat(distinct val)
without the group by
directive (!) to get one-line result.或者您可以使用
group_concat(distinct val)
而不使用group by
指令 (!) 来获得单行结果。
Or even cast(concat('[', group_concat(distinct val), ']') as json)
to get a proper json array: [15, 66, 578, 603, 751, 753, 801, 803]
.或者甚至
cast(concat('[', group_concat(distinct val), ']') as json)
以获得正确的 json 数组: [15, 66, 578, 603, 751, 753, 801, 803]
。
Read my Best Practices for using MySQL as JSON storage :)阅读我使用 MySQL 作为 JSON 存储的最佳实践:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.