JOIN 按照功能大緻分為如下三類:
<a href="http://s4.51cto.com/wyfs02/M02/89/C2/wKiom1gb3sjDU6M4AABL3sMjtiM021.png-wh_500x0-wm_3-wmp_4-s_4091312711.png" target="_blank"></a>
mysql> select * from a inner join score on a.sn=score.sn;
+----+---------+-------+----+-------+-------+
| id | name | sn | id | sn | score |
| 1 | mashen | 10086 | 1 | 10086 | 90 |
| 2 | haishen | 10087 | 2 | 10087 | 59 |
| 3 | haoge | 10088 | 3 | 10088 | 77 |
3 rows in set (0.24 sec)
mysql> select * from a join score on a.sn=score.sn;
3 rows in set (0.00 sec)
Inner join
産生的結果集中,是A和B的交集。
當2個關聯表字段相同時候 也可以用using(sn),這樣using 裡的字段顯示一次.....
mysql> select * from a join score using(sn);
+-------+----+---------+----+-------+
| sn | id | name | id | score |
| 10086 | 1 | mashen | 1 | 90 |
| 10087 | 2 | haishen | 2 | 59 |
| 10088 | 3 | haoge | 3 | 77 |
LEFT JOIN:産生表A的完全集,而B表中比對的則有值,沒有比對的則以null值取代
<a href="http://s4.51cto.com/wyfs02/M02/89/BF/wKioL1gb4aTin9ugAABacAx2rfs302.png-wh_500x0-wm_3-wmp_4-s_320553044.png" target="_blank"></a>
mysql> select * from a left join score on a.sn=score.sn;
+----+-----------+-------+------+-------+-------+
| id | name | sn | id | sn | score |
| 1 | mashen | 10086 | 1 | 10086 | 90 |
| 2 | haishen | 10087 | 2 | 10087 | 59 |
| 3 | haoge | 10088 | 3 | 10088 | 77 |
| 8 | left join | 11122 | NULL | NULL | NULL |
4 rows in set (0.00 sec)
##産生在A表中有而在B表中沒有的集合,在業務求新增的時候經常使用到的文法:
<a href="http://s4.51cto.com/wyfs02/M02/89/C0/wKioL1gb4wizUb2UAABaj4Q8oqk331.png-wh_500x0-wm_3-wmp_4-s_2341308678.png" target="_blank"></a>
mysql> select * from a left join score on a.sn=score.sn where score.id is null;
+----+-----------+-------+------+------+-------+
| id | name | sn | id | sn | score |
| 8 | left join | 11122 | NULL | NULL | NULL |
1 row in set (0.01 sec)
##産生在b表中有而在a表中沒有的集合,就是INNER JOIN
mysql> select * from a left join score on a.sn=score.sn where score.id is not null
+----+---------+-------+------+-------+-------+
| id | name | sn | id | sn | score |
| 1 | mashen | 10086 | 1 | 10086 | 90 |
| 2 | haishen | 10087 | 2 | 10087 | 59 |
| 3 | haoge | 10088 | 3 | 10088 | 77 |
RIGHT JOIN:産生表B的完全集,而A表中比對的則有值,沒有比對的則以null值取代,與left join 相反.
mysql> select * from a right join score on a.sn=score.sn
-> ;
+------+---------+-------+----+-------+-------+
| id | name | sn | id | sn | score |
| 1 | mashen | 10086 | 1 | 10086 | 90 |
| 2 | haishen | 10087 | 2 | 10087 | 59 |
| 3 | haoge | 10088 | 3 | 10088 | 77 |
| NULL | NULL | NULL | 4 | 10089 | 77 |
| NULL | NULL | NULL | 5 | 10090 | 70 |
5 rows in set (0.00 sec)
##産生在b表中有而在a表中沒有的集合,沒有比對顯示null
mysql> select * from a right join score on a.sn=score.sn where a.id is null;
+------+------+------+----+-------+-------+
| id | name | sn | id | sn | score |
| NULL | NULL | NULL | 4 | 10089 | 77 |
| NULL | NULL | NULL | 5 | 10090 | 70 |
版權聲明:原創作品,如需轉載,請注明出處。否則将追究法律責任
本文轉自 DBAspace 51CTO部落格,原文連結:http://blog.51cto.com/dbaspace/1869210