I've got three tables in a PostgreSQL db that looks like this: https://i.sstatic.net/1bNke.jpg
One user can belong to many projects, and one project can have many users, and I'm tying it together through a joined table called "userprojects".
Each table could look like this:
User
| id | firstname | lastname | email |
|----|-----------|----------|----------------|
| 1 | Joe | Green | [email protected] |
| 2 | Olle | Svensson | [email protected] |
| 3 | Erik | Yapp | [email protected] |
Project
| id | name | owner |
|----|---------------|----------------|
| 1 | Project X | [email protected] |
| 2 | Peanut Butter | [email protected] |
| 3 | Apollo 11 | [email protected] |
| 4 | RCPP | [email protected] |
Userprojects
| id | user_id | project_id |
|----|---------|------------|
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 3 |
| 4 | 3 | 3 |
Is there some form of inner(?) join that let's me query on users in a project (eg user_id found in userprojects) OR if the user is an owner of a project?
With the example above, an inner join query that looks like this:
SELECT "project".id, "project".name, "email"
FROM userprojects
INNER JOIN project ON userprojects.project_id = project.id
INNER JOIN "user" ON userprojects.user_id = "user".id
would return this:
| id | name | email |
|----|---------------|----------------|
| 1 | Project X | [email protected] |
| 2 | Peanut Butter | [email protected] |
| 3 | Apollo 11 | [email protected] |
| 4 | Apollo 11 | [email protected] |
What I wish to add to the query result is also the owner of each project if they are not found in that inner join query - notice that [email protected] is the owner of project RCPP but since that relation is not found in the userprojects table, it won't be returned in the query. Can I somehow also get my query to return those users, eg:
| id | name | email |
|-----|---------------|----------------|
| 1 | Project X | [email protected] |
| 2 | Peanut Butter | [email protected] |
| 3 | Apollo 11 | [email protected] |
| 4 | Apollo 11 | [email protected] |
| (?) | RCPP | [email protected] |