Search code examples
mysql

Minus MySQL Query


This is a quick sql query for an 'invite your friends to this group' script.

I have 2 tables: users and group_members. I'm trying to do a query that selects all of my friends--represented by the first select--and subtract all of my friends from the users that are already represented and part of the group--represented by the second select.

I keep getting syntax error and not sure why. When I run each select query by itself, it properly shows me all of my friends uid's (using the first query) as well as all of the uids of the group members (using the second query)

(SELECT a.uid, a.name_f, a.name_l, a.profile_pic, a.location FROM users a, friends b WHERE a.uid = b.friend_two AND b.friend_one = $VAR 
MINUS 
SELECT a.uid, a.name_f, a.name_l, a.profile_pic, a.location FROM users a, group_members m WHERE m.teamid = 95 and a.uid = m.userid)

Solution

  • MySQL does not support MINUS. You can usually recreate it through the use of a NOT IN subquery. This may do the job:

    SELECT
      a.uid,
      a.name_f,
      a.name_l,
      a.profile_pic, 
      a.location 
    FROM users a, friends b 
    WHERE a.uid = b.friend_two AND b.friend_one = $VAR
      AND a.uid NOT IN (
        SELECT subuser.uid FROM users subuser, group_members m WHERE m.teamid = 95 AND subuser.uid = m.uid
      )