Search code examples
joinouter-joinkdb

How to do full right outer join in kdb?


I have these two tables.

tab1:([]col1:`abc`def`ghi;col2:2 4 6);
tab2:([]col1:`def`ghi`ghi`rrr;col3:5 10 11 15);

I want to keep everything in the right table but duplicated the col1 to match the col1 in tab2. The closest I found is ij

tab2 ij 1! tab1

col1 col3 col2  
--------------
def  5    4   
ghi  10   6    
ghi  11   6  

However, I would like to produce this result:

col1 col3 col2
--------------
abc       2
def  5    4   
ghi  10   6   
ghi  11   6  

If there is other values in col1 in tab2, I am not interested to put that to result table: like I don't want `rrr in there.


Solution

  • How about this?

    q)uj[select from tab1 where not col1 in exec col1 from tab2;tab2 ij 1!tab1]
    col1 col2 col3
    --------------
    abc  2        
    def  4    5   
    ghi  6    10  
    ghi  6    11
    

    Here we apply union to a) everything from tab1 which is not present in tab2 and b) everything which is present in both tab1 and tab2.

    Not sure we can call this full outer right join because we don't want to include all records from tab2 (rrr in this case) but this is a terminology problem.