Subject in the title, i.e. are queries equal (if mysql is considered)
SELECT * FROM `tab1` RIGHT JOIN` tab` ON `table2`.`id` =` table1`. `id`
and
SELECT * FROM `tab1` RIGHT JOIN` tab2` USING (`id`)
if not, which is better and what is the difference?
Answer 1, authority 100%
USING (column_name (s)) is essentially a syntactic sugar for ON . According to docks – serves to specify a list of columns that must exist in both tables.
A USING expression like:
A LEFT JOIN B USING (C1, C2, C3, ...)
is semantically identical to ON :
A.C1 = B.C1 AND A.C2 = B.C2 AND A.C3 = B.C3, ...
While ON it is possible to “glue” columns with different names.
But with ON you can do a little more operations, for example, you can attach not only a column, but also a set of columns or even an entire condition, for example:
SELECT * FROM world.City JOIN world.Country ON (City.CountryCode = Country.Code) WHERE ...
Optional
USING – when listing fields in a request, it is not necessary to specify a prefix:
SELECT film.title, film_id // # film_id is specified without prefix
FROM film
JOIN film_actor USING (film_id)
WHERE ...
Same with ON :
SELECT film.title, film.film_id // # film.film_id prefix is required
FROM film
JOIN film_actor ON (film.film_id = film_actor.film_id)
WHERE ...
If you do not explicitly list the fields, but use select *
to join columns, then in the result set when ON the column will “pop up” twice, while with USING
– only once:
mysql & gt; create table t (i int);
insert t select 1;
create table t2 select * from t;
Query OK, 0 rows affected (0.11 sec)
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
Query OK, 1 row affected (0.19 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql & gt; select * from t join t2 on t.i = t2.i;
+ ------ + ------ +
| i | i |
+ ------ + ------ +
| 1 | 1 |
+ ------ + ------ +
1 row in set (0.00 sec)
mysql & gt; select * from t join t2 using (i);
+ ------ +
| i |
+ ------ +
| 1 |
+ ------ +
1 row in set (0.00 sec)
mysql & gt;
infa borrowed from enSO MySQL ON vs USING?