-- ------------------------------ Table structure for `a`-- ----------------------------DROP TABLE IF EXISTS `a`;CREATE TABLE `a` ( `aID` int(1) NOT NULL AUTO_INCREMENT, `aNum` char(20) DEFAULT NULL, PRIMARY KEY (`aID`)) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;-- ------------------------------ Records of a-- ----------------------------INSERT INTO `a` VALUES ('1', 'a20050111');INSERT INTO `a` VALUES ('2', 'a20050112');INSERT INTO `a` VALUES ('3', 'a20050113');INSERT INTO `a` VALUES ('4', 'a20050114');INSERT INTO `a` VALUES ('5', 'a20050115');-- ------------------------------ Table structure for `b`-- ----------------------------DROP TABLE IF EXISTS `b`;CREATE TABLE `b` ( `bID` int(1) NOT NULL AUTO_INCREMENT, `bName` char(20) DEFAULT NULL, PRIMARY KEY (`bID`)) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;-- ------------------------------ Records of b-- ----------------------------INSERT INTO `b` VALUES ('1', ' 2006032401');INSERT INTO `b` VALUES ('2', '2006032402');INSERT INTO `b` VALUES ('3', '2006032403');INSERT INTO `b` VALUES ('4', '2006032404');INSERT INTO `b` VALUES ('8', '2006032408');
mysql> select * from a;+-----+-----------+| aID | aNum |+-----+-----------+| 1 | a20050111 || 2 | a20050112 || 3 | a20050113 || 4 | a20050114 || 5 | a20050115 |+-----+-----------+5 rows in set
mysql> select * from b;+-----+-------------+| bID | bName |+-----+-------------+| 1 | 2006032401 || 2 | 2006032402 || 3 | 2006032403 || 4 | 2006032404 || 8 | 2006032408 |+-----+-------------+5 rows in set
left join
left join是以A表的记录为基础的,A可以看成左表,B可以看成右表,left join是以左表为准的.换句话说,左表(A)的记录将会全部表示出来,而右表(B)只会显示符合搜索条件的记录(例子中为: A.aID = B.bID).B表记录不足的地方均为NULL.
mysql> SELECT * FROM a LEFT JOIN b ON a.aID =b.bID;+-----+-----------+------+-------------+| aID | aNum | bID | bName |+-----+-----------+------+-------------+| 1 | a20050111 | 1 | 2006032401 || 2 | a20050112 | 2 | 2006032402 || 3 | a20050113 | 3 | 2006032403 || 4 | a20050114 | 4 | 2006032404 || 5 | a20050115 | NULL | NULL |+-----+-----------+------+-------------+5 rows in set
right join
和left join的结果刚好相反,这次是以右表(B)为基础的,A表不足的地方用NULL填充
mysql> SELECT * FROM a RIGHT JOIN b ON a.aID = b.bID;+------+-----------+-----+-------------+| aID | aNum | bID | bName |+------+-----------+-----+-------------+| 1 | a20050111 | 1 | 2006032401 || 2 | a20050112 | 2 | 2006032402 || 3 | a20050113 | 3 | 2006032403 || 4 | a20050114 | 4 | 2006032404 || NULL | NULL | 8 | 2006032408 |+------+-----------+-----+-------------+5 rows in set
inner join
相等联接或内联接,只显示出了 A.aID = B.bID的记录.这说明inner join并不以谁为基础,它只显示符合条件的记录
mysql> SELECT * FROM a INNER JOIN b ON a.aID =b.bID;+-----+-----------+-----+-------------+| aID | aNum | bID | bName |+-----+-----------+-----+-------------+| 1 | a20050111 | 1 | 2006032401 || 2 | a20050112 | 2 | 2006032402 || 3 | a20050113 | 3 | 2006032403 || 4 | a20050114 | 4 | 2006032404 |+-----+-----------+-----+-------------+4 rows in set
等同于
SELECT * FROM a,b WHERE a.aID = b.bID