When joining a data table, you can use either using or on. What are the similarities and differences?
ON is a more common usage. You can connect tables to On a field, multiple fields, or even a conditional expression. Example
SELECT * FROM world.City
JOIN world.Country
ON (City.CountryCode = Country.Code) WHERE ...
USING is useful when the field names associated with two tables are exactly the same.
SELECT ... FROM film JOIN film_actor
USING (film_id) WHERE ...
Another point is that there is no need to add qualifications in front of the associated fields. For example, film_id in the following statement SELECT does not need to be added film.
orfilm_actor.
SELECT film.title, film_id -- film_id is not prefixed
FROM film
JOIN film_actor USING (film_id)
WHERE ...
When the above SQL uses ON, we must do it in the following way:
SELECT film.title, film.film_id -- film.film_id is required here
FROM film
JOIN film_actor ON (film.film_id = film_actor.film_id)
WHERE ...
Pay attention to the restriction in the SELECT part film.film_id
. If there is only film_id
, it is not allowed, because it will be regarded as ambiguous (both tables have it).
ERROR 1052 (23000): Column 'film_id' in field list is ambiguous
SELECT *
, USING
when using , the associated field appears only once; ON
when using , the associated field appears twice.
create table t(i int);
insert t select 1;
create table t2 select*from t;
mysql> select*from t join t2 on t.i=t2.i;
+------+------+
| i | i |
+------+------+
| 1 | 1 |
+------+------+
1 row in set (0.00 sec)
mysql> select*from t join t2 using(i);
+------+
| i |
+------+
| 1 |
+------+
1 row in set (0.00 sec)