postgresql - AND/OR statements in SQL JOIN -


i have 2 tables: table1 , table2. can join them using id1 or id2. prefer use id1, in rows id1 missing, have use id2. following syntax correct:

select * table1  left join table2 b on (a.id1 not null , a.id1 = b.id1) or    (a.id2 not null , a.id2 = b.id2) 

it returns some results want sure if valid haven't seen used before.

are there better ways this?

looks have decent answer in comments, toss possibility ring, run both queries , union them.

select *  table1   left join table2 b     on a.id1 = b.id1 union select *  table1   left join table2 b     on a.id2 = b.id2 

the union eliminate duplicates between sets, , return records either condition true, or statement. performance wise, union little slower, gives easier control on sets. instance if want set 2 return results when id1 null, add clause. anyway hope helps.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -