【问题标题】:Get distinct values from MySQL JSON array从 MySQL JSON 数组中获取不同的值
【发布时间】:2016-09-15 10:12:29
【问题描述】:

我有一个 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 ...

没有重复。因为行也会很好。

有什么想法吗?

【问题讨论】:

  • 故事的寓意:将逗号分隔的数据存储在列中总是一个坏主意
  • 为此,您必须首先规范化您的数据。你有一个包含规范化约束值的表吗?

标签: mysql arrays json distinct concat


【解决方案1】:

抱歉,我遇到了类似的问题。解决方案是: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 by 指令 (!) 的 group_concat(distinct val) 来获得单行结果。

或者甚至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 :)

【讨论】:

    猜你喜欢
    • 2021-08-30
    • 2023-02-23
    • 2019-07-04
    • 2016-08-05
    • 2015-09-26
    • 2013-12-24
    • 1970-01-01
    • 2022-08-18
    • 2013-02-07
    相关资源
    最近更新 更多