Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Conditional Join

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;
like image 761
pepe Avatar asked Jun 04 '11 02:06

pepe


2 Answers

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;
like image 195
AJ. Avatar answered Sep 28 '22 07:09

AJ.


You are inventing syntax. The "IF" in MySQL is supported as:

  1. Statement, for use in stored procedures and triggers. Docs: http://dev.mysql.com/doc/refman/5.0/en/if-statement.html

  2. 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.

like image 30
dkamins Avatar answered Sep 28 '22 06:09

dkamins