1. 程式人生 > >MySQL中,關聯查詢的3種寫法(USING/ON)

MySQL中,關聯查詢的3種寫法(USING/ON)

看看下面三個關聯查詢的 SQL 語句有何區別?

SELECT * FROM score, student WHERE score.id = student.id ...
SELECT * FROM score JOIN student ON (score.id = student.id) WHERE ...
SELECT * FROM score JOIN student USING (id) WHERE ...
前兩種寫法,只是寫法不同而已,其功能完全相同;最後一種,會將同名的列,合併起來。
第一種,是傳統寫法,SQL89標準裡,就是這種;後面兩種,是在SQL92標準才有的!
mysql> select * from score;
+----+-------+
| id | score |
+----+-------+
|  1 |    60 |
|  2 |    75 |
|  4 |    90 |
+----+-------+
3 rows in set (0.00 sec)

mysql> select * from student;
+----+--------+
| id | name   |
+----+--------+
|  1 | 張三   |
|  2 | 李四   |
|  3 | 王五   |
+----+--------+
3 rows in set (0.00 sec)

mysql> select * from score, student where score.id=student.id;
+----+-------+----+--------+
| id | score | id | name   |
+----+-------+----+--------+
|  1 |    60 |  1 | 張三   |
|  2 |    75 |  2 | 李四   |
+----+-------+----+--------+
2 rows in set (0.09 sec)

mysql> select * from score join student on score.id=student.id;
+----+-------+----+--------+
| id | score | id | name   |
+----+-------+----+--------+
|  1 |    60 |  1 | 張三   |
|  2 |    75 |  2 | 李四   |
+----+-------+----+--------+
2 rows in set (0.00 sec)

mysql> select * from score join student using(id);
+----+-------+--------+
| id | score | name   |
+----+-------+--------+
|  1 |    60 | 張三   |
|  2 |    75 | 李四   |
+----+-------+--------+
2 rows in set (0.00 sec)

附,下面是SQL發展的簡要歷史:
1986年,ANSI X3.135-1986,ISO/IEC 9075:1986,SQL-86 
1989年,ANSI X3.135-1989,ISO/IEC 9075:1989,SQL-89 
1992年,ANSI X3.135-1992, ISO/IEC 9075:1992,SQL-92(SQL2) 
1999年,ISO/IEC 9075:1999, SQL:1999(SQL3) 
2003年,ISO/IEC 9075:2003, SQL:2003(SQL4) 
200N年,ISO/IEC 9075:200N, SQL:200N(SQLN)