Home > Software design >  sql select column from nested associated tables
sql select column from nested associated tables

Time:11-24

I have 3 tables in PostgreSQL:

  1. Projects
  2. Organizations
  3. User

Projects belongs to Organizations and Organizations belongs to User

I am trying to get projects which belongs to organizations which belongs to user where user.id is 1,

so I am trying to get all projects for user 1 from all organizations of this user

I just need raw sql code

CodePudding user response:

select p.* from users u
join organizations o on u.id = o.user_id
join projects p on o.id = p.organization_id
where u.id = 1;

CodePudding user response:

It depends a lot on how you have your relationship scheme. But what about nesting SQL statements?

SELECT * FROM projects 
WHERE organization_id in (
                       SELECT organization_id FROM organizations WHERE user_id = 1);
  • Related