Search code examples
mysqlsqljsoncorrelated-subquery

convert MySQL table aggregating multiple rows into JSON object


I am trying to convert a table, where I want to aggregate multiple rows into one JSON column. The old table has a primary key consisting of multiple columns, and two columns A and B. A should become the field name and B the value in the new table.

This is my Query so far:

INSERT INTO new_table (pk1, pk2, pk3, json_column)
SELECT DISTINCT pk1,
                pk2,
                pk3,
                JSON_INSERT(SELECT JSON_ARRAYAGG(JSON_OBJECT(A, B)) from old_table
                            WHERE
                             pk1 = old.pk1 AND pk2 = old.pk2 AND pk3 = old.pk3)
FROM old_table AS old;

My IDE ist telling me, that "old_table" cannot be resolved in the JSON_INSERT-Statement, but I cannot figure out why.


Solution

  • JSON_INSERT is actually the way to insert json into jsons, but you don't need to, so skip it.

    But your query would be right if you do

    INSERT INTO new_table (pk1, pk2, pk3, json_column)
    SELECT DISTINCT pk1,
                    pk2,
                    pk3,
                    JSON_INSERT((SELECT JSON_ARRAYAGG(JSON_OBJECT(A, B)) from old_table
                                WHERE
                                 pk1 = old.pk1 AND pk2 = old.pk2 AND pk3 = old.pk3))
    FROM old_table AS old;
    

    but actually you need only

    INSERT INTO new_table (pk1, pk2, pk3, json_column)
    SELECT DISTINCT pk1,
                    pk2,
                    pk3,
                    (SELECT JSON_ARRAYAGG(JSON_OBJECT(A, B)) from old_table
                                WHERE
                                 pk1 = old.pk1 AND pk2 = old.pk2 AND pk3 = old.pk3)
    FROM old_table AS old;