The following query works:
SELECT
SUM(sales),
date
FROM
sales
INNER JOIN
exchange_rates
USING(date)
But this fails:
SELECT
SUM(sales),
date
FROM
sales
INNER JOIN
exchange_rates
ON sales.date = exchange_rates.date
Why does this fail — I thought they were the same? How would I fix the second query?
In general, if you use the
USINGclause, the column you are joining on does not need to be aliased in theSELECTlist. The database knows that the column is not ambiguous– there is no potential thatsales.datewill be different thanexchange_rates.date. If you use theONclause, on the other hand, there is the potential for ambiguity. Obviously, in this case, you the human knows that there is no ambiguity, it’s just that the syntax doesn’t guarantee that.should work (I’m adding the
GROUP BYas well just to be explicit)