0

I have a huge database 'Job seeker' having multiple table like username, skills, qualification, job, social media, etc. One user can have multiple columns on job, social media, etc. table. Now if I use simple inner join I get multiple columns for single user.

Select user.user_id, user.name, s.skill_name, s.type , q.qualification, j.job_name, s_url
from username user
inner join skills s on s.skill_user = user.user_id
inner join qualification q on q.qualification_user = user.user_id
inner join job j on j.job_user = user.user_id

But what if I want top 1 row for each user. How can I do it?

Edit: Is there some other way to do this instead of using distinct?

3
  • 2
    Please consider following these suggestions.
    – mustaccio
    Commented Jul 20, 2022 at 18:55
  • How do you define 'top'?
    – jjanes
    Commented Jul 20, 2022 at 20:18
  • Not necessarily top, just one row for one user.
    – RedVel
    Commented Jul 21, 2022 at 5:04

1 Answer 1

1

A simple way is to use distinct on ()

Select distinct on (user.user_id) user.user_id, user.name, s.skill_name, s.type , q.qualification, j.job_name, s_url
from username "user"
  join skills s on s.skill_user = user.user_id
  join qualification q on q.qualification_user = user.user_id
  join job j on j.job_user = user.user_id
order by user.user_id;

This picks a "random" row from the result.

A more complicated way (but possibly more efficient) would be to pick only one row for each of the joined tables:

select distinct on (user.user_id) user.user_id, user.name, s.skill_name, s.type , q.qualification, j.job_name, s_url
from username "user"
  join lateral ( 
     select * 
     from skills s 
     where s.skill_user = user.user_id -- only for the "outer" user
     limit 1 -- only one skill for that user
  ) as s on true
  ... follow the same pattern for the other tables ...

The on true is necessary because a join needs a join condition but as we limit the rows for the current user in the derived table, there is no need to repeat that condition in the join condition.

1
  • Thank you so much I was trying the distinct() but was getting very frustrated and confused due to small errors. I used the first query and now it is working perfectly.
    – RedVel
    Commented Jul 21, 2022 at 10:40

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.