How to list every JSON Array element separately within MySQL Query?

meallhour :

I have written following MySQL Json Array query. The Mysql version is 8.0.18-commercial

select 
networkInfo->>"$.*" as network,
servers->>"$[*]" as server
from table1
where id = 56;

The output has 2 columns network and server of JSON type

network              server
---                  ---
[                    [
    "Linux123",          "Server123",
    "RHEL",              "Server1231",
    "abc.com"            "Server1232"
]                    ]

I want to modify the SELECT query such that the output has a separate row for every server:

network                      server
---                          ----  
[                             Server123
    "Linux123",
    "RHEL",
    "abc.com"
]

[                             Server1231
    "Linux123",
    "RHEL",
    "abc.com"
]

[                             Server1232
    "Linux123",
    "RHEL",
    "abc.com"
]
Nick :

You can use JSON_TABLE to extract the different server values from servers, then CROSS JOIN that to the networks value for the given id:

SELECT t1.networkInfo->>"$.*" AS network, j.server
FROM table1 t1
CROSS JOIN JSON_TABLE(t1.servers, 
                      "$[*]" COLUMNS (
                        server VARCHAR(20) PATH '$'
                        )
                      ) j
WHERE t1.id = 56

Output (I've had to hack up a demo based on an expectation of table structure):

network                             server
["abc.com", "Linux123", "RHEL"]     Server123
["abc.com", "Linux123", "RHEL"]     Server1231
["abc.com", "Linux123", "RHEL"]     Server1232

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=386847&siteId=1