1

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.

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.