Skip to content
Advertisement

How to get only specific record from multiple tables?

I have tables ‘table1‘, ‘table2’,’table3‘ and ‘table4’ . ’table1’ has a column ‘account’ on basis of I need to get record from ‘table2’ or ‘table3’ or ‘table4’ with respect of another column ‘user_id’.

I am using query like

SELECT * 
FROM table1 
LEFT OUTER JOIN table2 ON table1.user_id = table2.user_id
LEFT OUTER JOIN table2 ON table1.user_id = table2.user_id
LEFT OUTER JOIN table3 ON table1.user_id = table3.user_id

using this I am getting lots of NULL values because each record of table1 will have only record in either ‘table2’ or ‘table3’ or ‘table4’.

Present output is like –

t1.user_id  | t1.post_id     | t2.token   | t3.token  | t4.token
 1          |      1         |   xyz      |   NULL    | NULL      
 1          |      1         |   NULL     |   abc     | NULL  
 1          |      1         |   NULL     |   NULL    | etc  

needed is like

 t1.user_id | t1.post_id     | token 
 1          |      1         |   xyz       
 1          |      1         |   abc  
 1          |      1         |   etc

t2,t3 and t4 can have more than 1 column to select.

Advertisement

Answer

It would be much simpler to use the COALESCE() function:

SELECT 
    t1.user_id, 
    t1.post_id, 
    COALESCE(t2.Token, t3.Token, t4.Token) AS Token
FROM table1 
LEFT OUTER JOIN table2 ON table1.user_id = table2.user_id
LEFT OUTER JOIN table2 ON table1.user_id = table2.user_id
LEFT OUTER JOIN table3 ON table1.user_id = table3.user_id
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement