mysql - 从 MySQL JSON 数组中获取不同的值

标签 mysql arrays json distinct concat

我得到了一个 MySQL 数据表,其中包含一个包含值列表的 JSON 列:

约束表

 ID | CONSTRAINT_TYPE | CONSTRAINT_VALUES
----+-----------------+--------------------------------
 '2'| 'testtype'      |'[801, 751, 603, 753, 803]'
 ...| ...             | ...

我想要的是一个不同的、逗号分隔的 JSON 值列表。我用 group_concat 尝试过,但它适用于数组,而不是单个值。
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 ...

没有重复。因为行也不错。

想法,有人吗?

最佳答案

很抱歉进行死灵,但我遇到了类似的问题。解决方法是: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]
二、使用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
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] .

阅读我的 Best Practices for using MySQL as JSON storage :)

关于mysql - 从 MySQL JSON 数组中获取不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39508478/

相关文章:

php - 查询未显示任何结果

mysql - 显示最后到第一个 mysql 条目

c - Robotc(c修改)如何传递一个char数组变量

ios - 将swift数组转换为对象以进行json序列化

ios - 在 ios 中解析和推送嵌套的 json 对象

php - 一个 php 文件中的多个查询,我尝试编写代码,但我没有完成

mysql - 根据行号查找行

python - 不使用 numpy.logic_or 的逻辑或

c++ - 如何在不创建新类的情况下部分填充 C++ 模板模板参数

java - 如何在 Retrofit2 中发布消息?