mysql> select table1.id as id,book,author from table1, table2 where table1.id=table2.id; +------+------+--------+ | id | book | author | +------+------+--------+ | 2 | c++ | zhang | | 3 | php | wang | +------+------+--------+ 2 rows in set (0.00 sec) mysql> select * from table1 inner join table2 using (id); +------+------+--------+ | id | book | author | +------+------+--------+ | 2 | c++ | zhang | | 3 | php | wang | +------+------+--------+ 2 rows in set (0.00 sec)
mysql> select * from table1 left join table2 using (id); mysql> select * from table2 right join table1 using (id); 结果集: +------+------+--------+ | id | book | author | +------+------+--------+ | 1 | java | NULL | | 2 | c++ | zhang | | 3 | php | wang | +------+------+--------+
Right Join 右外连接
右外连接和左外连接是类似的。为了方便数据库便于访问,推荐使用左外连接代替右外连接。
注意事项
两个表求差集的方法
如果求 左表 - 右表 的差集,使用类似下面的SQL:
1
SELECT left_tbl.* FROM left_tbl LEFT JOIN right_tbl ON left_tbl.id = right_tbl.id WHERE right_tbl.id IS NULL;
例如
1 2 3 4 5 6 7
mysql> select table1.* from table1 left join table2 on table1.id = table2.id where table2.id is null; +------+------+ | id | book | +------+------+ | 1 | java | +------+------+ 1 row in set (0.00 sec)
mysql> select id, book, author from table1 join table2 using (id); mysql> select table1.id, book, author from table1 join table2 on table1.id=table2.id; 结果集: +------+------+--------+ | id | book | author | +------+------+--------+ | 2 | c++ | zhang | | 3 | php | wang | +------+------+--------+
但是下面两个有些许不同,使用on时候,重复的部分会被输出两次。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
mysql> select * from table1 join table2 using (id); +------+------+--------+ | id | book | author | +------+------+--------+ | 2 | c++ | zhang | | 3 | php | wang | +------+------+--------+ 2 rows in set (0.00 sec) mysql> select * from table1 join table2 on table1.id=table2.id; +------+------+------+--------+ | id | book | id | author | +------+------+------+--------+ | 2 | c++ | 2 | zhang | | 3 | php | 3 | wang | +------+------+------+--------+ 2 rows in set (0.00 sec)
SQL1 : SELECT * FROM t1, t2 JOIN t3 ON (t1.i1 = t3.i3); SQL2 : SELECT * FROM (t1, t2) JOIN t3 ON (t1.i1 = t3.i3); SQL3 : SELECT * FROM t1, (t2 JOIN t3 ON (t1.i1 = t3.i3));
SQL1 : SELECT ... FROM t1 NATURAL JOIN t2 NATURAL JOIN t3; SQL2 : SELECT ... FROM t1, t2, t3 WHERE t1.b = t2.b AND t2.c = t3.c; SQL3 : SELECT ... FROM t1, t2, t3 WHERE t1.b = t2.b AND t2.c = t3.c AND t1.a = t3.a;
一句话: 连接分为内连接,和外连接。(本来还有第三类交叉连接,交叉连接就是直接求笛卡尔积,在MySQL中等同于内连接)。内连接中还有一种自然连接,相当于不用加where语句,可以直接通过列名自动连接起来。外连接也有左外自然连接(natural left join)。
注意:mysql貌似不支持全外链接,可以只用left join union right join来实现full outer join。