As you can see below, I am checking to see if the current user is in user_a
or user_b
columns of table friends.
Depending on where the current user is located, I want to get his corresponding friend.
Somehow I can't get this syntax to work and wonder if anyone can tell me what's wrong (I get an error on line 3 near IF user_a = 2
.
SELECT *
FROM friends
IF user_a = 2 THEN
JOIN user_profiles ON friends.user_b = user.profiles.user_id
WHERE user_a = 2
AND accepted = 1;
ELSEIF user_b = 2 THEN
JOIN user_profiles ON friends.user_a = user_profiles.user_id
WHERE user_b = 2
AND accepted = 1;
END IF;
You can do it with a UNION:
select f.*, up_a.* from friends f
inner join user_profiles up_a on f.user_a=up_a.user_id
where f.user_b=2 and f.accepted=1
union
select f.*, up_b.* from friends f
inner join user_profiles up_b on f.user_b=up_b.user_id
where f.user_a=2 and f.accepted=1;
You are inventing syntax. The "IF" in MySQL is supported as:
Statement, for use in stored procedures and triggers. Docs: http://dev.mysql.com/doc/refman/5.0/en/if-statement.html
Function, for use in choosing one of alternate expressions for a result column. Docs: http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_if
You appear to be doing something else entirely.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With