... the same column of each table will appear once
Yes Natural Join
does that.
... and only the relational rows will come.
I don't know what that means.
I disagree with those who are saying: do not use Natural Join
. But it is certainly true that if you plan to use Natural Join
for your queries, you must design the schema so that (loosely speaking) 'same column name means same thing'.
Then this exercise is teaching you the dangers of having same-named columns that do not mean the same thing. The danger is sometimes called the 'connection trap' or 'join trap'. (Not really a trap: you just need to learn ways to write queries over poorly-designed schemas.)
A more precise way to put that: if you have columns named the same in two different tables, the column must be a key of at least one of them. So:
city
is not a key in any of those tables,
so should not get 'captured' in a Natural Join
.
salesman_id
is not a key in table customer
,
so should not get 'captured' in the join from table orders
.
The main way to fix up this query is by renaming some columns to avoid 'capture' (see below). It's also worth mentioning that some dialects of SQL allow:
SELECT *
FROM orders
NATURAL JOIN customer ON customer_id
...
The ON column(s)
phrase means: validate that the only columns in common between the two tables are those named. Otherwise reject the query. So your query would be rejected.
Renaming means that you shouldn't use SELECT *
. (Anyway, that's dangerous for 'production code' because your query might produce different columns each time there's a schema change.) The easiest way to tackle this might be to create three Views for your three base tables, with the 'accidental' same-named columns given some other name. For this one query:
SELECT ord_no, purch_amt, ord_date, customer_id,
salesman_id AS order_salesman_id
FROM orders
NATURAL JOIN (SELECT customer_id, cust_name,
city AS cust_city, grade,
salesman_id AS cust_salesman_id
FROM customer) AS customer_grr
NATURAL JOIN (SELECT salesman_id, name,
city AS salesman_city,
commission
FROM salesman) AS salesman_grr
I'm using explicit AS
to show renaming. Most dialects of SQL allow you to omit that keyword; just put city cust_city, ...
.