¿Cómo aplicar la unión externa en 2 mesas usando una mesa intermedia?

table1 | id | value
--------------------
          1 | john
          2 | frank
          3 | patel
          4 | jim

table2 | id | value
--------------------
          6 | steve
          7 | tim
          8 | sunny
          9 | bhaskar

merged | tabid1 | tabid2
------------------------------
         3      | 7
         4      | 8

salida necesaria:

    output  | tabid1 | tabval1 | tabid2 | tabval2
              1      | john    | NULL   | NULL
              2      | frank   | NULL   | NULL
              3      | patel   | 7      | tim
              4      | jim     | 8      | sunny
              NULL   | NULL    | 6      | steve
              NULL   | NULL    | 9      | bhaskar

Lo intenté:

SELECT * 
FROM table1
LEFT JOIN merged m1 ON table1.id = m1.tabid1, merged m2
RIGHT JOIN table2 ON table2.id = m2.tabid2

But its giving 16 rows instead of required 6

preguntado el 01 de febrero de 12 a las 04:02

3 Respuestas

select table1.id,table1.value,table2.id,table2.value 
     from table1 left join merged on table1.id=merged.tabid1 
            left join table2 on merged.tabid2=table2.id 
union 
select table1.id,table1.value,table2.id,table2.value 
     from table2 left join merged on table2.id=merged.tabid2
     left join table1 on merged.tabid1=table1.id ;

or with right join:

SELECT * FROM 
    table1 LEFT JOIN merged on table1.id=merged.tabid1 
           LEFT JOIN table2 ON merged.tabid2=table2.id  
UNION 
SELECT * FROM 
    table1 RIGHT JOIN merged on table1.id=merged.tabid1 
           RIGHT JOIN table2 ON merged.tabid2=table2.id WHERE table1.id IS NULL;

Respondido 01 Feb 12, 09:02

+1, but a little hard to read with the abbreviated table names. - Adam Wenger

This works, I submitted an edit to it to use @jerrymouse's tablenames - Paraguas

SELECT  
       table1.id    tabid1,  
       table1.value tabvalue1,  
       table2.id    tabid2,  
       table2.value tabvalue2  
  FROM merged  
  FULL OUTER JOIN table1 ON merged.tabid1 = table1.id;  
  FULL OUTER JOIN table2 ON merged.tabid2 = table2.id;  

Respondido 01 Feb 12, 22:02

there is no FULL OUTER JOIN in mysql - guido

SELECT table1.id AS tabid1, table1.value AS tabval1,
       table2.id AS tabid2, table2.value AS tabval2
FROM table1
LEFT JOIN merged m1 ON table1.id = m1.tabid1
RIGHT OUTER JOIN table2 ON table2.id = m1.tabid2

I don't know why you felt the need to join merged twice there.

Respondido 01 Feb 12, 08:02

This only returns four rows. It is not the answer jerrymouse is looking for. - Paraguas

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.