0

I am struggling with an SQL query on the inner join. I want to have it so it joins on the field not the same as the $user_id. Hope that made sense, this might be easier to understand:

if ($user_id = wallfriends.mem_id_from) {
INNER JOIN wallfriends ON wallusers.mem_id = wallfriends.mem_id_to
} else if ($user_id = wallfriends.mem_id_to) {
INNER JOIN wallfriends ON wallusers.mem_id = wallfriends.mem_id_from
}

My Current query:

SELECT * FROM wallusers 
INNER JOIN wallfriends ON wallusers.mem_id = wallfriends.mem_id_from
WHERE ((wallfriends.mem_id_from =".$user_id.") OR (wallfriends.mem_id_to =".$user_id.")) AND wallfriends.confirm=1

Thanks in advance

3 Answers 3

3

I think what you need is a putting a ternary comparison on the sql string

$sql = " SELECT * FROM wallusers 
INNER JOIN wallfriends ON wallusers.mem_id = ".( $user_id == "wallfriends.mem_id_to"?"wallfriends.mem_id_from":"wallfriends.mem_id_to")."
WHERE wallfriends.confirm=1";
Sign up to request clarification or add additional context in comments.

2 Comments

Hang on, doesn't this perform the comparison between $user_id and the literal string wallfriends.mem_id_to in PHP, rather than between $user_id and the value of the mem_id_to column in the wallfriends table in SQL (as I had understood the problem to be)?
@eggyal yes, that is what it does. That is what I understood from the question. If you wanted to compare the string directly to the table and not use its content to decide on what to join, you could do INNER JOIN (($user_id = wallfriends.mem_id_to AND wallusers.mem_id = wallfriends.mem_id_from) OR ($user_id = wallfriends.mem_id_from AND wallusers.mem_id = wallfriends.mem_id_to)) ;)
1

Try this ::

SELECT * 
FROM wallusers 
INNER JOIN wallfriends ON wallusers.mem_id = wallfriends.mem_id_from
WHERE 
(wallfriends.mem_id_from =".$user_id.") 
OR 
(wallfriends.mem_id_to =".$user_id.")

1 Comment

I need the inner join to have the where clause. INNER JOIN wallfriends ON wallusers.mem_id = wallfriends.mem_id_from/wallfriends.mem_id_to depending on the $user_id
1
SELECT * FROM wallusers 
INNER JOIN wallfriends ON 
wallusers.mem_id = 
CASE WHEN 
wallfriends.mem_id_from =".$user_id." 
THEN wallfriends.mem_id_to 
ELSE wallfriends.mem_id_from
END
WHERE wallfriends.confirm=1

3 Comments

this looks promising, although im getting an error right syntax to use near 'WHERE wallfriends.confirm=1 LIMIT 0, 30' at line 8
You're missing the END keyword (to terminate the CASE expression) before WHERE.
Thanks for the END. I forgot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.