I have three tables
- project (id, user_id, project_name)
- project_roles (id, user_id, project_id)
- users (id, nickname)
I want to fetch all projects for user that has id 1
and I also want to get projects where this user has record in project_roles
So, if user has project A and B and this user has row in project_roles for project C, I want to fetch projects A, B and C
I tried this:
SELECT *
from project
WHERE user_id = 1
OR (project.id = project_roles.project_id WHERE project_roles.user_id = 1)
example data:
USERS TABLE
- id: 1, nickname: ‘test’
PROJECTS table
- id: 7777, user_id: 2, project_name: ‘NAME1’
- id: 8888, user_id: 1, project_name: ‘NAME2’
- id: 9999, user_id: 1, project_name: ‘NAME3’
PROJECT_ROLES table
- id: 5, user_id: 1, project_id: ‘7777’
I want to fetch all 3 projects for user 1 because projects with id 8888 and 9999 has user_id: 1
and there is project_roles data where user_id is 1 so I want to get project 7777 also
4
Answers
Thank you everyone for helping me.
This is answer which works for me.
Tried to replicate sample data, its a bit different than what you have provided but the context is the same.
Schema (MySQL v8.0)
Query #1
You should use set operator
union
for that :In case a user is in
PROJECTS
table andPROJECT_ROLES
table, the set operatorUNION
will remove duplicates.First query (above UNION) returns projects that are in the project table. This is simple.
Second query returns projects in project_roles which are not in project for that user. Also returns the project name. This assumes the projects table is not empty and has at least one record for each project present in project_roles.