Boe*_*ger 5 mysql arrays json concat distinct
我得到了一个 MySQL 数据表,其中包含一个包含值列表的 JSON 列:
约束表
ID | CONSTRAINT_TYPE | CONSTRAINT_VALUES
----+-----------------+--------------------------------
'2'| 'testtype' |'[801, 751, 603, 753, 803]'
...| ... | ...
Run Code Online (Sandbox Code Playgroud)
我想要的是一个不同的、逗号分隔的 JSON 值列表。我用 group_concat 尝试过,但它适用于数组,而不是单个值。
SELECT group_concat(distinct constraint_values->>'$')
FROM constraint_table c
WHERE c.constraint_type = "testtype";
Run Code Online (Sandbox Code Playgroud)
实际结果:
[801, 751, 603, 753, 803],[801, 751],[578, 66, 15],...
Run Code Online (Sandbox Code Playgroud)
我的目标结果:
801, 751, 603, 753, 803, 578, 66, 15 ...
Run Code Online (Sandbox Code Playgroud)
没有重复。因为行也不错。
想法,有人吗?
抱歉,死灵术,但我也遇到过类似的问题。解决方案是:JSON_TABLE()从MySQL 8.0开始可用。
首先,将行数组合并为单行数组。
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]
Run Code Online (Sandbox Code Playgroud)
其次,使用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
Run Code Online (Sandbox Code Playgroud)
请参阅https://dev.mysql.com/doc/refman/8.0/en/json-table-functions.html#function_json-table
注意group by val获取不同的值。你也可以order他们和一切......
或者您可以group_concat(distinct val)不使用group by指令 (!) 来获得一行结果。
或者甚至cast(concat('[', group_concat(distinct val), ']') as json)获得一个正确的 json 数组:[15, 66, 578, 603, 751, 753, 801, 803]。
阅读我的使用 MySQL 作为 JSON 存储的最佳实践:)