Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Left Join in Mysql?

This is my first Table.

table1

Then the second one is

table2

Now I am trying to do Left join like this

SELECT t1.StackID FROM t1 LEFT JOIN t2 on t1.StackID=t2.StackID

Output

output

I am confused here, Is this the correct output? Is not this supposed to return only the 5 rows which is present in left side table.

like image 350
Giri Avatar asked Sep 04 '13 12:09

Giri


3 Answers

It's correct output. You are doing LEFT JOIN, so for every record in LEFT table DBMS will 'concatenate' the corresponding RIGHT table record(-s) (and NULL, if there's no corresponding record for the JOIN condition; also remember, that if there are more that 1 corresponding record - all will be joined - this issue is why you're getting not only 5 records from 1-st table).

The thing you're trying to achieve should be done by either DISTINCT modifier, i.e.

SELECT DISTINCT t1.StackID FROM t1 LEFT JOIN t2 ON t1.StackID=t2.StackID;

More about JOIN in SQL you can read here.

like image 81
Alma Do Avatar answered Sep 17 '22 00:09

Alma Do


There is a simple example of left join:-

SELECT * FROM a JOIN b LEFT JOIN c ON (c.key=a.key) LEFT JOIN d ON (d.key=a.key) 
WHERE b.key=d.key;
like image 35
Learner Avatar answered Sep 21 '22 00:09

Learner


These extra repeated values of StackId are coming from the join, just use DISTINCT to get those only 5 values:

SELECT DISTINCT t1.StackID 
FROM t1 
LEFT JOIN t2 on t1.StackID=t2.StackID;
  • SQL Fiddle Demo
like image 31
Mahmoud Gamal Avatar answered Sep 17 '22 00:09

Mahmoud Gamal