Update
How I can select the rows from a table that when ordered
- the first element matches some row
- the second element matches the next row
- the third element the next row after the second row
- the forth element the next row after the third row
- and so on until the end of values in array?
The Logic
Supposing I have these rows as result of a query (table token
holds id
and word
and table positioning
holds id
and position
):
id | word | textblockid |sentence |position
5 | Fear | 5 | 1 | 1
8 | of | 5 | 1 | 2
6 | the | 5 | 1 | 3
7 | Dark | 5 | 1 | 4
9 | is | 5 | 1 | 5
I can have this spread in the table with different textblockids, sentences and positions.
I want to transform in this:
id | word | textblockid | sentence |position
10 | Fear of the Dark | 5 | 1 | 1
9 | is | 5 | 1 | 2
I'm doing a function that receives an array with the ids to merge, something like merge_tokens('{5,8,6,7}')
.
I insert the new word Fear of the Dark
in the table token
and get the generated id (as in example, id
is 10
). This is easy.
The Question
I need to update the id
of the first word (in this case, Fear
) to 10
and delete the next words(of
,the
,Dark
).
My doubt is how I can perform these operations. I think I need to SELECT
from an ordered table where the first row id matches the first element in the id array, the second row id matches the second element id array and so on, and after this, update the first element and remove the next ones.
I can't delete just delete the other rows by id because they are used in other words. I only will delete the of
where the previous is Fear
, the next is of
and the next Dark
. Following this rule, I only can delete the
where the previous is of
, the other previous Fear
and the next is Dark
.
As example, I can have in the same table something like that can't be affected:
id | word | textblockid |sentence |position
6 | the | 8 | 3 | 10
11 | sound | 8 | 3 | 21
8 | of | 8 | 3 | 12
6 | the | 8 | 3 | 13
7 | mountain | 8 | 3 | 14