0

employees table with columns:
id (pk) BIGINT, name TEXT, email TEXT, work_locations BIGINT[].

work_locations columns contains the location table ids.

location table with columns:
id (pk) BIGINT, lat DECIMAL(12,9), long DECIMAL(12,9).

I want a result like

id  name  email            lat,      long   
1   name  [email protected]  23.345   54.3678

I am not able to join two table on work_locations and ids.
How to join these two tables?

3
  • What if an employee has more than one work location? What output do you expect then? One row for each location? Commented Mar 25, 2021 at 12:08
  • yes, a new row for each location. Commented Mar 25, 2021 at 12:10
  • It is very bad design to store references to data in an array. The query will be inefficient. You should normalize the table. Commented Mar 25, 2021 at 13:31

2 Answers 2

2

You can join using the ANY operator:

select e.*, 
       l.lat, 
       l.long
from employees e
  join locations l on l.id = any(e.work_locations)
order by e.id;

In general I would recommend to not store foreign keys in arrays like that. You should think about a properly normalized model with a many-to-many link table between employees and locations

Sign up to request clarification or add additional context in comments.

Comments

0

You can unnest():

select e.*, l.*
from employees e cross join lateral
     unnest(work_locations) wl(work_location) left join
     locations l
     on wl.work_location = l.id;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.