解析出 Mysql 中的 JSON 列数组数据 5.7

Parsing out JSON column Array data in Mysql 5.7

我有这样的数据

Product Siz Color     RFIDs
GO1199  5XL WHIT    "[\"300ED89F335000B333B8CA8D\",\"300ED89F335000B333B8C5F3\",\"E2009A4050026AF000001928\"]"
GO1189  LAR WHIT    "[\"300ED89F335000B333B8CA8D\",\"300ED89F335000B333B8C5F3\",\"E2009A4050026AF000001928\"]"
GO1179  LAR WHIT    "[\"300ED89F335000B333B8CA76\",\"300ED89F335000B333B8C7C8\",\"300ED89F335000B333B8C58D\"]",
GO1169  LAR WHIT    "[\"300ED89F335000999A72D381\",\"300ED89F3350007FC4FDCCFB\",\"300ED89F3350007FC4FDDEF9\"]",
GO1199  LAR WHIT    "[\"300ED89F3350007FC4FDDF5E\",\"300ED89F3350007FC4FDDDE1\",\"300ED89F3350007FC4FDDDDF\"]"

最后一列是与该产品相关联的 RFID 数组。我想用 SQL

把它表达出来并像这样显示
Product Siz Color     RFID
GO1199  5XL WHIT    300ED89F335000B333B8CA8D
GO1199  5XL WHIT    300ED89F335000B333B8C5F3
GO1199  5XL WHIT    E2009A4050026AF000001928
GO1189  LAR WHIT    300ED89F335000B333B8CA8D
GO1189  LAR WHIT    300ED89F335000B333B8C5F3
GO1189  LAR WHIT    E2009A4050026AF000001928

谢谢。

抱歉,这是 5.7 而不是 8

在 MySQL 8.0 中,使用 json_table():

select t.product, t.size, t.color, x.rfid
from mytable t
cross join json_table(t.rfids, '$[*]' columns (rfid varchar(50) path '$')) x

在早期版本中,它有点复杂。基本上你需要 table 个数字来取消嵌套数组:

select t.product, t.size, t.color, 
    json_unquote(json_extract(t.rfids, concat('$[', n.i, ']'))) rfid
from mytable t
inner join (select 0 i union all select 1 union all select 2) n
    on n.i < json_length(t.rfids)

您可以使用更多数字扩展子查询,以处理每个数组超过 3 个项目。

Demo on DB Fiddle:

product | size | color | rfid                    
:------ | :--- | :---- | :-----------------------
GO1199  | 5XL  | WHIT  | E2009A4050026AF000001928
GO1199  | 5XL  | WHIT  | 300ED89F335000B333B8C5F3
GO1199  | 5XL  | WHIT  | 300ED89F335000B333B8CA8D
GO1189  | LAR  | WHIT  | E2009A4050026AF000001928
GO1189  | LAR  | WHIT  | 300ED89F335000B333B8C5F3
GO1189  | LAR  | WHIT  | 300ED89F335000B333B8CA8D
GO1179  | LAR  | WHIT  | 300ED89F335000B333B8C58D
GO1179  | LAR  | WHIT  | 300ED89F335000B333B8C7C8
GO1179  | LAR  | WHIT  | 300ED89F335000B333B8CA76
GO1169  | LAR  | WHIT  | 300ED89F3350007FC4FDDEF9
GO1169  | LAR  | WHIT  | 300ED89F3350007FC4FDCCFB
GO1169  | LAR  | WHIT  | 300ED89F335000999A72D381
GO1199  | LAR  | WHIT  | 300ED89F3350007FC4FDDDDF
GO1199  | LAR  | WHIT  | 300ED89F3350007FC4FDDDE1
GO1199  | LAR  | WHIT  | 300ED89F3350007FC4FDDF5E