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
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.
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.
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 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With