When to and when not to NATURAL JOIN?

懵懂的女人 提交于 2019-12-08 11:26:25

问题


I have been having this doubt for a while now, after some practices in SQL I started to ask myself: 'When is the right time to use NATURAL JOIN'?

Due to the enormous size of the database example that I'm using to practice my SQL skills I'm just going to put two sample queries here. Let's say I want to

Find, for each item, the total quantity sold by the departments on the second floor

The sample answer of this question is:

SELECT Item.ItemName, SUM(SaleQTY)
  FROM Item INNER JOIN Sale INNER JOIN Department
  ON Item.ItemID = Sale.ItemID
  AND Department.DepartmentID = Sale.DepartmentID
  WHERE DepartmentFloor = 2
  GROUP BY Item.ItemName
  ORDER BY Item.ItemName;

However when doing this question myself I only used NATURAL JOIN and here is my attempt:

SELECT Item.ItemName, SUM(SaleQTY)
  FROM Item NATURAL JOIN SALE NATURAL JOIN Department
  WHERE DepartmentFloor = 2
  GROUP BY Item.ItemName
  ORDER BY Item.ItemName

And it produced the exact same output as the sample answer:

ItemName           SUM(SaleQTY)
Boots - snakeproof      2
Camel saddle            1
Elephant polo stick     1
Hat - polar explorer    3
Pith helmet             1
Pocket knife - Nile     2
Sextant                 2`

I understand that the reason for an INNER JOIN is to ensure the integrity of the data by these conditions applied in the code and eliminate any data that does not satisfy them. But still I'm wondering, is NATURAL JOIN sufficient enough to crack this problem?

If not, what are some important rules to follow?

来源:https://stackoverflow.com/questions/41085629/when-to-and-when-not-to-natural-join

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