0

Here is the query:

select IF ((t1.emp_id IS NOT NULL), t2.username, '') 
from t1, t2 
where t1.user_id = "285" AND t2.id = t1.emp_id

It works fine, but if t1.emp_id is NULL it will not return result because of this part AND t2.id = t1.emp_id but this part secure me that I will get exact t2.id if t1.emp_id is not NULL. Is there a way to handle it ?

The idea is if t1.emp_id is not null then to return t2.username based on relation t1.emp_id = t2.id but in this case when t1.emp_id is null it doesn't return result, because of last part of query. If I remove last part it will not returns me exact row from t2.

1
  • 2
    Sample data, desired results, and an explanation of the logic would all help. Why are you not using proper, explicit, standard, readable JOIN syntax. Commented Jun 12, 2020 at 13:59

2 Answers 2

1

I think you want a LEFT JOIN. My best guess is:

select coalesce(t2.username, '')
from t1 left join
     t2 
     on t2.id = t1.emp_id 
where t1.user_id = 285;
Sign up to request clarification or add additional context in comments.

Comments

0

use following query & try again.

select t1.emp_id, t2.username
from t1, t2 
where t1.user_id = "285" AND t2.id = t1.emp_id AND t1.emp_id is NOT NULL;

1 Comment

This will not work, because I want to return results, whether or not there is t1.emp_id

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.