I have two tables and an in-between like
project |
---|
id |
group |
---|
id |
project_group |
---|
project |
group |
How can I get all projects by a groupId
, where an entry (projectId, groupId)
exists in project_group
?
I have two tables and an in-between like
project |
---|
id |
group |
---|
id |
project_group |
---|
project |
group |
How can I get all projects by a groupId
, where an entry (projectId, groupId)
exists in project_group
?
Since only Project_group has information for both project and group it's the only way to relate those two tables. In this scenario we need to join project with group so that we can find a project associated to a particular group.
Let's assume that we need to find all the project associated with group 1. The to select all the project - group relationship for group 1 we can write:
select project, group from project_group where group=1
This will return only the relationship but we need all the project related information such as code, name, cost etc.
On the other hand id from project table is same as project from project_group table. So we can join both the table with inner join on those columns as below:
select * from project p inner join project_group pg on p.id=pg.group
Now we will combine both the queries:
select * from project p inner join project_group pg on p.id=pg.group
and pg.group=1
It will return all the columns from project and project_group table. But to have all the columns from only project table you can use:
select p.* from project p inner join project_group pg on p.id=pg.group
and pg.group=1
`group`
and it's fine – theonlygusti Mar 09 '21 at 10:52