There is a simplified table mytable
with columns ('id', 'mycolumn')
of int
and varchar(255)
respectively.
What's the fastest way to find a row with the longest common right part (the longest tail) for current string in the mycolumn
? The table is huge.
As example, for the string "aaabbbkr84"
we'd find 2 - "wergerbkr84"
by the longest found tail "bkr84":
1 - "gbkyugbk9"
2 - "wergerbkr84"
3 - "gbkyugbk4".
To increase the performance, my thoughts were to create another column with the reverted strings. However I'm not sure if it helps and there is no better way. That way I would look up (until I get 0 results to return to the previous one) to look up for
SELECT id, mycolumn FROM mytable
where reverted like '4%';
SELECT id, mycolumn FROM mytable
where reverted like '48%';
SELECT id, mycolumn FROM mytable
where reverted like '48r%';
SELECT id, mycolumn FROM mytable
where reverted like '48rk%';
SELECT id, mycolumn FROM mytable
where reverted like '48rkb%'; ' <-- looking for this one
SELECT id, mycolumn FROM mytable
where reverted like '48rkbb%'; ' 0 results.
0 results found, taking a step back:48rkb
. Which means 2 - "wergerbkr84"
is the answer.
1 query for to find a row by the longest tail would be preferable (I have a loop of queries above as you see). However, the performance is #1.
Thanks a lot.