Skip to content
Advertisement

Provide array of ids and get rows with repeated rows

I have the table where I wand to do a query to get same rows multiply times

Races Table:

id name location
1 fast race London
2 cool race New York
3 super race Berlin

I want to do query where I will search races in table by id and get results with repeated rows something like this

SELECT location FROM races WHERE id = [1, 2, 3, 1, 1, 1, 2, 2]

And get the following:

locations = [
 "London",
 "New York",
 "Berlin",
 "London",
 "London",
 "London",
 "New York",
 "New York",
]

Is this possible to do in postgresSQL?

Advertisement

Answer

You can unnest the array then join to it:

select r.location
from races r
  join unnest(array[1, 2, 3, 1, 1, 1, 2, 2]) as t(id) on r.id = t.id;

If you want the result sorted by the array position, use `with ordinality:

select r.location
from races r
  join unnest(array[1, 2, 3, 1, 1, 1, 2, 2]) with ordinality as t(id,idx) on r.id = t.id
order by t.idx;
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement