Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining Left & Right Join in mysql query

I am joining 2 tables -tbl1 and tbl2. Left join give all data from tbl1 which is in tbl2 or only on tbl1. Right join gives data from tbl2 which is don't exists in tbl1.

I want to combine both results.

What is the best way to do this so that i get all data from tbl1 and tbl2 ?

like image 445
Obhaso Avatar asked Aug 11 '12 07:08

Obhaso


4 Answers

The only you can do that is by using UNION. MySQL doesn't support FULL JOINjust like in MSSQL.

SELECT * 
FROM tbl1 t1 
       LEFT JOIN tbl2 t2
          ON t1.col = t2.col
UNION 
SELECT * 
FROM tbl1 t1 
       RIGHT JOIN tbl2 t2 
          ON t1.col>= t2.<col

SEE HERE: Simulating FULL JOIN in MYSQL

By the way, UNION has optional keyword ALL,when the ALL is omitted, UNION automatically selects DISTINCT rows from the resultset.

EXAMLE:

SELECT *
FROM   tableA
UNION ALL
SELECT *
FROM   tableA

this can result duplicates rows

ColA    ColB
==================
1       John
2       Jade
2       Jade
3       Hello

BUT if you omit the word ALL

SELECT *
FROM   tableA
UNION
SELECT *
FROM   tableA

this can result distinct rows only

ColA    ColB
==================
1       John
2       Jade
3       Hello
like image 126
John Woo Avatar answered Oct 10 '22 01:10

John Woo


What you want is FULL JOIN

LEFT JOIN + RIGHT JOIN = FULL JOIN

So try this:

SELECT * FROM tbl1
LEFT JOIN tbl2 ON tbl1.id = tbl2.id
UNION
SELECT * FROM tbl1
RIGHT JOIN tbl2 ON tbl1.id = tbl2.id

The UNION clause combines the results of two SQL queries into a single table of all matching rows.

like image 25
Himanshu Jansari Avatar answered Oct 10 '22 03:10

Himanshu Jansari


Here's an alternative that can be easily extended if you have a full join of more than 2 tables:

SELECT t1*, t2.* 
FROM 
    ( SELECT col
      FROM tbl1
    UNION
      SELECT col
      FROM tbl2
    ) AS d
  LEFT JOIN tbl1 AS t1 
    ON t1.col = d.col
  LEFT JOIN tbl2 AS t2
    ON t2.col = d.col ;
like image 29
ypercubeᵀᴹ Avatar answered Oct 10 '22 01:10

ypercubeᵀᴹ


you have to use FULL OUTER JOIN, But mysql doesnt support it.. You could do this for getting the result:

 SELECT * 
FROM tbl1 t1 LEFT JOIN tbl2 t2
ON t1.<col> = t2.<col>
UNION 
SELECT * 
FROM tbl1 t1 RIGHT JOIN tbl2 t2 
ON t1.<col>= t2.<col> 
like image 41
Joe G Joseph Avatar answered Oct 10 '22 02:10

Joe G Joseph