簡體   English   中英

如何從 MYSQL 中的 JSon 中提取信息

[英]How to extract the information from JSon in MYSQL

我有樣本數據

 set @j = '[{"id": 1, "title": "Mohan"}, 
            {"id": 2, "title": "Rama"}, 
            {"id": 3, "title": "IP Mana"}]';
  Select REPLACE(REPLACE(REPLACE(JSON_EXTRACT(@j, '$**.*'),"[",""),"]",""),'"','') AS Name_List from  tbl_employee 

我得到這樣的數據:

    NameList
 1, Mohan, 2, Rama, 3, IP Mana

我正在嘗試像這樣獲得 output :

NameList
 1 : Mohan, 2 : Rama, 3 : IP Mana

任何人都可以建議我。

在 MySQL 8.0 中,您可以為此使用json_table()

select id, title
from json_table(
    @j,
    '$[*]'
    columns (id int path '$.id', title varchar(20) path '$.title')
) t;

或者,如果您希望將結果作為標量值:

select group_concat(id, ' : ', title separator ', ') res
from json_table(
    @j,
    '$[*]'
    columns (id int path '$.id', title varchar(20) path '$.title')
) t;

在早期版本中,您通常會使用數字表和json_extract()

select 
    json_extract(@j, concat('$[', n.n, '].id')) id,
    json_extract(@j, concat('$[', n.n, '].title')) title
from (select 0 n union all select 1 union all select 2 union all select 3) n
where json_extract(@j, concat('$[', n, ']')) is not null

暫無
暫無

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

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