Understanding Natural Join in SQL

折月煮酒 提交于 2021-01-20 09:04:55

问题


So I am fairly new to SQL and currently I am stuck with the concept of Natural Join.

Currently I understand that the Natural Join operator joins tables by matching all columns with the same names and discarding duplicate columns and discarding rows which do not match.

So recently I came across a question, pretty basic really, however i couldn't wrap my head around it.

So there are 2 relations R(A,B,C) and S(A,B,D)

    A B C           A B D
    6 8 7           5 8 7
    6 6 7           6 6 7
    7 8 6           6 8 6

How many rows would the following query produce?

SELECT * FROM R NATURAL JOIN S

So instantly I see two columns which 'match' they being A and B. By using Natural Join would it take into account both A and B or just A and as such, what information would be discarded.

The answer is 2 rows. Can someone please explain the method of getting 2 rows?

Thanks!

Are the 2 rows by any chance

    A B D
    6 6 7
    6 6 6

If so, I may delete this question


回答1:


This is too long for a comment. Don't use natural joins. Don't bother learning natural joins. They are an abomination.

Why? The join conditions are based on columns with the same names. Natural joins do not even take declared foreign key relationships into account. This can be quite dangerous. Or -- in my case -- because almost all my tables have CreatedAt and CreatedBy, they are useless anyway.

Instead, list the join keys. In your case (because you have select *), the using clause is most appropriate:

SELECT * 
FROM R JOIN
     S
     USING (A, B);

This also has the advantage that the keys are explicitly shown in the query, which greatly reduces the scope for errors.




回答2:


At the the risk of oversimplifying, NATURAL JOIN performs a join on columns of the same name.

Here is a re-write (among many other possible rewrites) using more genrealized operators:

SELECT R.A, R.B, C, D
  FROM R, S
 WHERE R.A = S.A
       AND R.B = S.B

The result has four columns and two rows:

| A | B | C | D |
-----------------
| 6 | 6 | 7 | 7 |
| 6 | 8 | 7 | 6 |


来源:https://stackoverflow.com/questions/48054868/understanding-natural-join-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!