Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

join if entry doesn't exists in second table

I have two tables which are selected an joined,

Table1

PK    Val1    Val2     FK
1     a       b        10
2     c       d        11
3     e       f
4     g       h        12

Table2

PK    Val3
10     X
11     Y
12     Z

When I do a select on this both tables with an inner join and all the Val-Columns I get this result:

Result
PK    Val1    Val2     Val3
1     a       b        X
2     c       d        Y
4     g       h        Z

As you can see the third entry is missing. What I want is something like this:

Result
PK    Val1    Val2     Val3
1     a       b        X
2     c       d        Y
3     e       f
4     g       h        Z

How do I have to modify the joinquery

SELECT ... FROM Table1 INNER JOIN Table2 On Table1.FK = Table2.PK

Thank you, Karl

like image 627
abc Avatar asked Oct 19 '12 07:10

abc


People also ask

Can we apply joins on 2 tables which has no related data?

Yes, you can! The longer answer is yes, there are a few ways to combine two tables without a common column, including CROSS JOIN (Cartesian product) and UNION. The latter is technically not a join but can be handy for merging tables in SQL.

How do you join two tables that are not related?

The most common way to join two unrelated tables is by using CROSS join, which produces a cartesian product of two tables. For example, if one table has 100 rows and another table has 200 rows then the result of the cross join will contain 100x200 or 20000 rows.

Can you inner join a table that doesn't have matching records?

The JOIN or INNER JOIN does not return any non-matching rows at all. It returns only the rows that match in both of the tables you join. If you want to get any unmatched rows, you shouldn't use it. The LEFT JOIN and the RIGHT JOIN get you both matched and unmatched rows.

How can I get data that is not present in another table?

How to Select All Records from One Table That Do Not Exist in Another Table in SQL? We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries.


1 Answers

use LEFT JOIN instead of INNER JOIN

SELECT ... FROM Table1 LEFT JOIN Table2 On Table1.FK = Table2.PK

basically, INNER JOIN returns record where there is atleast a match on the other table. While LEFT JOIN returns all records on the table specified on the left side whether it has a match or none.

btw, LEFT OUTER JOIN is identical to LEFT JOIN

SQLFiddle Demo

like image 200
John Woo Avatar answered Sep 23 '22 15:09

John Woo