问题描述
我得到了一个MySQL数据表,其中的JSON列包含值列表:
I got a MySQL data Table, with a JSON Column containing a list of Values:
CONSTRAINT_TABLE
CONSTRAINT_TABLE
ID | CONSTRAINT_TYPE | CONSTRAINT_VALUES
----+-----------------+--------------------------------
'2'| 'testtype' |'[801, 751, 603, 753, 803]'
...| ... | ...
我想要的是一个独特的,用逗号分隔的JSON值列表.我用group_concat尝试过,但是它适用于数组,而不是单个值.
What I want to have is a distinct, comma-seperated List of JSON-Values. I tried it with group_concat, but it applys to the arrays, not the single values.
SELECT group_concat(distinct constraint_values->>'$')
FROM constraint_table c
WHERE c.constraint_type = "testtype";
实际结果:
[801, 751, 603, 753, 803],[801, 751],[578, 66, 15],...
我的目标结果:
801, 751, 603, 753, 803, 578, 66, 15 ...
无重复.因为行也很好.
without duplicates. As rows would be nice, too.
想法,有人吗?
推荐答案
对不起,请您提前告知我,但我遇到过类似的问题.解决方案是:JSON_TABLE()
自MySQL 8.0起可用.
Sorry for necromancing, but I've encountered similar issue. The solution is: JSON_TABLE()
available since 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]
第二,使用json_table
将数组转换为行.
Second, use json_table
to convert the array into rows.
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
请参见 https://dev.mysql.com/doc/refman/8.0/zh-CN/json-table-functions.html#function_json-table
注意group by val
以获得不同的值.您还可以order
它们以及所有内容...
Notice group by val
for getting distinct values. You can also order
them and everything...
或者您可以在不使用group by
指令(!)的情况下使用group_concat(distinct val)
获得单行结果.
Or you can use group_concat(distinct val)
without the group by
directive (!) to get one-line result.
甚至cast(concat('[', group_concat(distinct val), ']') as json)
以获得正确的json数组:[15, 66, 578, 603, 751, 753, 801, 803]
.
Or even cast(concat('[', group_concat(distinct val), ']') as json)
to get a proper json array: [15, 66, 578, 603, 751, 753, 801, 803]
.
阅读我的使用MySQL作为JSON存储的最佳做法:)
这篇关于从MySQL JSON数组获取不同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!