Query from MySQL nested json field and return a subset of json
P粉265724930
P粉265724930 2024-03-28 12:06:49
0
1
470

I have the following lines:

id Product Log Creation time
1 <json string, see below> 2022-07-13 07:13:00

Example json data:

{
    "products": [
        {
            "logs": [{
                "log_time": "2022-07-13 01:30:00",
                "log_type": "manual",
                "log_info": "some text"
            }],
            "product_id": 123,
            "time": "2022-07-12 01:30:00"
        }, 
        {
            "logs": [],
            "product_id": 124,
            "time": "2022-07-13 01:31:00"
        }
    ]
}

For example searching product_id 124, it should return the entire row, but the json field only contains matching objects:

id Product Log Creation time
1 {"logs":[],"product_id":124,"time":"2022-07-13 01:31:00"} 2022-07-13 07:13:00

It's also fine if the resulting output contains the original "shape" of json:

{
    "products": [
        {
            "logs": [],
            "product_id": 124,
            "time": "2022-07-13 01:31:00"
        }
    ]
}

P粉265724930
P粉265724930

reply all(1)
P粉129168206
SELECT test.id, 
       test.created_at, 
       JSON_OBJECT('products', JSON_ARRAYAGG(jsontable.log_data))
FROM test
CROSS JOIN JSON_TABLE(test.product_logs,
                      '$.products[*]' COLUMNS (log_data JSON PATH '$')) jsontable
WHERE jsontable.log_data->'$.product_id' = 124
GROUP BY 1,2

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=26541a1e241be02680ba97a78f0791 c2一个>

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template