tags:

views:

58

answers:

3

I have tables as below

table A

emp_code | emp_name

table B

emp_code | id

table C

emp_code | id

I want to get emp_name so I do:

SELECT a.emp_name 
  FROM A a, B a 
 WHERE a.emp_code = b.emp_code

Now I want to capture a case when id in table B is not null and greater than 0 then it should compare a.emp_code with emp_code from table C (like SELECT c.emp_code FROM C c, B b WHERE c.id = b.id) otherwise do as above.

+1  A: 

Hard to tell what you are looking for, but you could start from here:

SELECT *
       ,COALESCE(c.id, b.id) AS chosen_id
FROM A AS a
LEFT JOIN B AS b
    ON a.emp_code = b.emp_code 
LEFT JOIN C AS c
    ON c.emp_code = a.emp_code
    AND b.id IS NOT NULL
    AND b.id > 0
Cade Roux
+2  A: 

You could UNION two SELECTs, the first on B excluding records with 0 or null, and the second on C including only records where B has 0 or null.

Carlos Gutiérrez
A: 

Your description of what you want doesn't make much sense, so I tried two differnt queries that might get you want you want (If b has a code why do you want c's code, wouldn't you really want b's code in that case?):

SELECT a.emp_name , case when b.emp_code >0 or b.id is not null then c.emp_code, else b.emp_code end as emp_code 
FROM A a
LEFT JOIN B b 
    ON a.emp_code = b.emp_code 
LEFT JOIN C c 
    ON c.emp_code = b.emp_code 

SELECT a.emp_name , case when b.emp_code <0 or b.emp_code is null then c.emp_code, else b.emp_code end as emp_code 
FROM A a
LEFT JOIN B b 
    ON a.emp_code = b.emp_code 
LEFT JOIN C c 
    ON c.emp_code = a.emp_code 
HLGEM
Actually "id" is like an indicator which tell me if it is not null or > 0 pick emp_code from table C
Vishal
I wanted to check if b.id is not null or > 0, you haven't even used it in your code.
Vishal
I added it to the case statment above, but truly you don't need the is not null because if it is greater than 0 is it not null.
HLGEM
Agreed, but I need to check for null before I can compare it for > 0 (so its "not null and > 0", incorrect in the comment above) else whatever compares with null returns false.
Vishal