簡體   English   中英

從 MySQL JSON 數組中獲取不同的值

[英]Get distinct values from MySQL JSON array

我得到了一個 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]


閱讀我使用 MySQL 作為 JSON 存儲的最佳實踐:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM