小编典典
它主要是语法糖,但是有一些区别值得注意:
ON 是两者中更通用的。一个人可以在一个列,一组列甚至一个条件上联接表。例如:
SELECT * FROM world.City JOIN world.Country ON (City.CountryCode = Country.Code) WHERE ...
*当两个表共享它们所连接的名称完全相同的列时,*USING 很有用。在这种情况下,您可能会说:
SELECT ... FROM film JOIN film_actor USING (film_id) WHERE ...
另一种不错的方法是不需要完全限定连接列:
SELECT film.title, film_id -- film_id is not prefixed
FROM film
JOIN film_actor USING (film_id)
WHERE ...
为了说明这一点,使用 ON 进行上述操作,我们必须编写:
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 ...
注意条款中的film.film_id限定条件SELECT。仅仅说这是无效的,film_id因为这会造成歧义:
错误1052(23000):字段列表中的“ film_id”列不明确
至于 select * ,连接列在结果集中ON出现两次,而在以下位置只出现一次USING:
mysql> 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> 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)
mysql>
2020-05-17