Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Natural join with more than one common attribute in two tables [duplicate]

I can understand how natural join works when the two tables have only one common attribute. What if they have two ones? Table 1 have 3 attributes: A, B, C Table 2 has 3 attribute: A, B, D

First two rows in table 1:

1 2 3
4 5 6

First two rows in table 2:

1 3 4
8 5 8

What is the result of a natural join between the two tables?

like image 524
Hiep Avatar asked Oct 14 '14 03:10

Hiep


2 Answers

In the case of your two records above, nothing will be matched. It will look for the case when A & B in the left table match A & B in the right table.

like image 161
Dan Avatar answered Oct 22 '22 17:10

Dan


Natural Join is a variant of INNER JOIN where join condition is implicit on common column from both tables. In your case, the query in Natural Join can be written as below which will not return any result since it will try to match both A and B

select *
from table1
natural join table2

The same can be written in Inner Join like below

select t1.*
from table1 t1
inner join table2 t2
on t1.a = t2.a and t1.b = t2.b

See for yourself Fiddle Demo

like image 30
Rahul Avatar answered Oct 22 '22 15:10

Rahul