I have a table containing info of tree nodes.
element_type_id | root_id | parent_id | number_in_parent
4 1 1 1
4 1 1 2
4 1 1 5
4 2 66 1
4 2 66 2
4 2 66 7
I need to copy all elements from root_id 2 into root_1. But, if element_type_id and number matches, the inserting element must be renumbered into a minimal free number of sequence 1..99.
For example: the first one has numbers 1,2,5. The second one - 1,2,3. The result must be 1,2,3,4,5,7.
To generate "free numbers" i could do like this:
SELECT "number" FROM (
SELECT generate_series(1, (
SELECT MAX("number") + 99 as "number"
FROM tree_elements te2
WHERE root_id = 1 AND element_type_id = 4)) AS "number"
EXCEPT SELECT "number"
FROM tree_elements te
WHERE root_id = 1 AND element_type_id = 4
) s
ORDER BY "number" LIMIT 99;
But I don't realize how to get it work within copy query (whatever it is. cause i don't know that either).
How do I do that? How to solve the problem by using PostgreSQL? Which way to dig? Does PostgreSQL have similar functions? Or may be I have to use loops, inner loops etc.?