Search code examples
sqlsubqueryfeedif-statement

IF..ELSE-statement in SQL SELECT?


I'm trying to make a user activity feed that only displays users' activities who are friends of the logged-in user.

The fields user1 and user2 are the friend request sender and friend request receiver. The problem is that the logged-in user could be in either field so I'm wondering how I can make an if..else statement for this particular issue.

Basically I want:

IF user2 is $log_username SELECT user1 FROM friends...
ELSE
SELECT user2 FROM friends.

The boldfaced code(subquery) is the one I'm referring to specifically.

$sql = "
SELECT * FROM status 
WHERE author in (
        SELECT user2 FROM friends 
        WHERE user1='$log_username'
          AND accepted='1' 
           OR user2='$log_username' 
          AND accepted='1'
    ) AND type='a' 
";

Any help is greatly appreciated.


Solution

  • The IF within an SQL Statement is CASE. Something like this (not sure if this gives you what you want but just to demonstrate the concept).

    $sql = "
    SELECT * FROM status 
    WHERE author in (
            SELECT CASE WHEN user2 = '$log_username' THEN user1 ELSE user2
                   END
             FROM friends 
            WHERE user1='$log_username'
              AND accepted='1' 
               OR user2='$log_username' 
              AND accepted='1'
        ) AND type='a' 
    ";