Must a natural join be on a shared primary key?

戏子无情 提交于 2019-12-13 09:47:14

问题


Suppose I perform A natural join B, where:

A's schema is: (aID), where (aID) is a primary key.
B's schema is: (aID,bID), where (aID, bID) is a composite primary key.

Would performing the natural join work in this case? Or is it necessary for A to have both aID and bID for this to work?


回答1:


NATURAL JOIN returns rows with one copy each of the common input table column names and one copy each of the column names that are unique to an input table. It returns a table with all such rows that can be made by combining a row from each input table. That is regardless of how many common column names there are, including zero. When there are no common column names, that is a kind of CROSS JOIN aka CARTESIAN JOIN. When all the column names are common, that is a kind of INTERSECTION. All this is regardless of PKs, UNIQUE, FKs & other constraints.

NATURAL JOIN is important as a relational algebra operator. In SQL it can be used in a certain style of relational programming that is in a certain sense simpler than usual.

For a true relational result you would SELECT DISTINCT. Also relations have no special NULL value whereas SQL JOINs treat a NULL as not equal to a NULL; so if we treat NULL as just another value relationally then SQL will sometimes not return the true relational result. (When both arguments have a NULL for each of some shared columns and both have the same non-NULL value for each other shared column.)




回答2:


A "natural" join uses the names of columns to match between tables. It uses any matching names, regardless of key definitions.

Hence,

select . . .
from a natural join b

will use AId, because that is the only column with the same name.

In my opinion, natural join is an abomination. For one thing, it ignores explicitly declared foreign key relationships. These are the "natural join" keys, regardless of their names.

Second, the join keys are not clear in the SELECT statement. This makes debugging the query much more difficult.

Third, I cannot think of a SQL construct where adding a column or removing a column from a table takes a working query and changes the number of rows in the result set.

Further, I often have common columns on my tables -- CreatedAt, CreatedOn, CreatedBy. Just the existence of these columns precludes using natural joins.




回答3:


Natural join will require both.

Regards,

Ted



来源:https://stackoverflow.com/questions/46554617/must-a-natural-join-be-on-a-shared-primary-key

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