Home  >  Q&A  >  body text

Query from MySQL nested json field and return a subset of json

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粉265724930P粉265724930205 days ago427

reply all(1)I'll reply

  • P粉129168206

    P粉1291682062024-03-29 00:02:15

    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

    reply
    0
  • Cancelreply