Home > Back-end >  Need a hand with many-to-many query
Need a hand with many-to-many query

Time:08-02

Im kinda new to these relationship databases and joins and I cant figure this one out.

Basically I need to fetch users uuid's from the db that are in a meeting with my user and not to fetch my uuid.

I have three tables users, participants and meetings. Participants is the join table for many to many relationship between the two other tables. Atleast that is what I think it is.

Tables

The problem is that I cant combine the two queries that I have created and those two queries that I created are not the solution to this.

This gives me all the meeting id's that there are associated with my users.id:

select meetings.id as 'meetingId'
from users 
inner join participants on participants.users_id = users.id and users.id = 1
 inner join meetings on participants.meetings_id = meetings.id;

Results

And this gives me the user that is associated with meetingId's that are fetched from the above query:

select users.username, users.uuid, meetings.id as 'meetingId', meetings.timestamp, meetings.description
from meetings 
inner join participants on participants.meetings_id = meetings.id
 inner join users on users.id = participants.users_id
 and meetings.id = 2
 and users.id != 1;

Results

CodePudding user response:

Try the following:

SELECT users.username, users.uuid, meetings.id as 'meetingId',
       meetings.timestamp, meetings.description
FROM participants p1
     inner join participants p2 on p2.meetings_id = p1.meetings_id
     inner join users on users.id = p2.users_id
     inner join meetings on meetings.id = p2.meetings_id
WHERE p1.users_id=1 AND p2.users_id<>1
  • Related