Here’s my problem:
I have a table with 4 columns (type = array, one-dimension) with values like:
ID c1 c2 c3
1 {1, 2, 3} {10, 20, 30} {100, 200, 300}
2 {4, 5, 6} {11, 22, 33} {111, 222, 333}
I was wondering if it is possible to get a result like the following:
select ID, c1, c2, c3 from t1 where c3 = 200 (<---- pseudo-statement!)
Result:
1, 2, 20, 200
or
select ID, c1, c2, c3 from t1 where c3 = 333
Result:
1, 6, 33, 333
So what I want is to get the corresponding values of the value in the where-statement.
Is there a way to get a solution for this?
(Edit1: simplified, Edit2: wider scope)
Solutions for any array-length. Also returns all hits, even at multiple positions in one or more arrays at the same time.
If you know the fixed length of the one-dimensional array, you can hard-code it in
generate_series(), for the simplest and fastest solution:If all arrays in
c3have the same unknown length, you can generalize at very little cost:Note that I use the convenient function
generate_subscripts()here.For a greater subscripts than the upper limit, array elements are just
NULLand drop out of the query.If the unknown length of the array in
c3actually varies, you can generalize some more, at a higher cost:Finally, for non-standard array subscripts in addition, the same could be done like this:
Instant testbed: