user1011713
user1011713

Reputation: 279

SQL Statement with a condition

I have the following Query:

SELECT a.name_f, a.uid, a.name_l, a.profile_pic, b.position FROM users a groups_members b, WHERE a.uid = b.userid AND b.group_id=$group_var

This works great and brings back all of the users' info as well as their positions within the group for any certain group that I want to call. When a group attends an event, on that event page I want to call the above function but also an extra statement that finds whether that user is confirmed. So I run the following query:

SELECT a.name_f, a.uid, a.name_l, a.profile_pic, b.position, c.confirmed FROM users a groups_members b, event_users c WHERE a.uid = b.userid AND b.group_id='$group_var' and c.event_id ='$event_var' and a.uid = c.userid

This also works great but here's where my problem arises. Let's assume that a certain group has created an event and subsequently, all of the users have been dumped into the event_users table. My 2nd query would still work and show every user in that group as well as his or her and confirmed setting but when a new user joins the group and selects his or her position, that new user is not returned in my second query and therefore, the event that shows all of the users' along with their position, does not account for any new users that were added after the event was created.

I hope that doesn't sound too confusing. Here are my tables:

event_users || id, event_id, userid, confirmed    

groups_members || id, userid, group_id, position

users || uid, name_f, name_l, profile

My question is how can I basically collect all of the current group members and subsequently if they have been entered into the event_users table, what is their confirmed status. I do not want to run queries on my group page that accounts for new users and puts them into any events that the group has

Upvotes: 1

Views: 104

Answers (1)

barbalion
barbalion

Reputation: 175

Use left joins:

    SELECT 
      a.name_f, a.uid, a.name_l, a.profile_pic, b.position, c.confirmed 
    FROM users a 
    JOIN groups_members b on a.uid = b.userid
    LEFT JOIN event_users c on a.uid = c.userid
    WHERE b.group_id='$group_var' and c.event_id ='$event_var'

You will be getting NULL as a value of c.confirmed if there is no correspondent record in event_users table. You may use coalesce() function to put there default value:

     coalesce(c.confirmed, 0)

or

     coalesce(c.confirmed, 'not subscribed yet')

Upvotes: 2

Related Questions