Search code examples
mysqlsqlclause

How to Use IN Clause as well as AND clause in SQL together


SELECT * 
FROM `Events` 
WHERE `UserID` IN (SELECT `BeingFollowed` FROM `Followers` WHERE `Follower` = us)

Ok so above is my query and i'm trying to get all the events made by my followers and the us variable is a parameter in a stored routine function which is my UserID but i'm not following myself but i want to get my events also and every event has a UserID and I wanted to get all of my followers events as well as the ones i have all within the same query


Solution

  • That's what OR does:

    SELECT * 
    FROM `Events` 
    WHERE `UserID` IN (SELECT `BeingFollowed` FROM `Followers` WHERE `Follower` = us)
    OR `UserID` = us
    

    You could also add yourself to the subquery, but that's probably slower:

    SELECT * 
    FROM `Events` 
    WHERE `UserID` IN (
      SELECT `BeingFollowed` FROM `Followers` WHERE `Follower` = us
      UNION ALL
      SELECT us
    )