亲宝软件园·资讯

展开

mysql join类型 MySQL七种JOIN类型小结

IllTamer 人气:3
想了解MySQL七种JOIN类型小结的相关内容吗,IllTamer在本文为您仔细讲解mysql join类型的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:mysql,join类型,mysql,join,下面大家一起来学习吧。

        在开始之前,我们创建两个表用于演示将要介绍的其中JOIN类型。

建表

CREATE TABLE `tbl_dept` (
   `id` INT(11) NOT NULL AUTO_INCREMENT,
   `deptName` VARCHAR(30) DEFAULT NULL,
   `locAdd` VARCHAR(40) DEFAULT NULL,
   PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE `tbl_emp` (
   `id` INT(11) NOT NULL AUTO_INCREMENT,
   `name` VARCHAR(20) DEFAULT NULL,
   `deptId` VARCHAR(11) NOT NULL,
   PRIMARY KEY (`id`),
   KEY `fk_dept_id` (`deptId`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

初始化数据

七种JOIN

1. A ∩ B

 SELECT < select_list >
 FROM TableA A
 INNER JOIN TableB B # 共有
 ON A.Key = B.Key

2. A ( = A ∩ B + A* )

 SELECT < select_list >
 FROM TableA A
 LEFT JOIN TableB B
 ON A.Key = B.Key

3. B ( = A ∩ B + B* )

 SELECT < select_list >
 FROM TableA A
 RIGHT JOIN TableB B
 ON A.Key = B.Key

 

4. A* ( = A - A ∩ B )

 

 SELECT < select_list >
 FROM TableA A
 LEFT JOIN TableB B
 ON A.Key = B.Key # ON时主表保留
 WHERE B.Key IS NULL # 筛选A表数据

5. B* ( = B - A ∩ B )

 SELECT < select_list >
 FROM TableA A
 RIGHT JOIN TableB B
 ON A.Key = B.Key
 WHERE A.Key IS NULL

6. A ∪ B

 

 SELECT < select_list >
 FROM TableA A
 FULL OUTER JOIN TableB B ## FULL OUTER 仅oracle支持
 ON A.Key = B.Key

 

7. A ∪ B - A ∩ B

 SELECT < select_list >
 FROM TableA A
 FULL OUTER JOIN TableB B
 ON A.Key = B.Key
 WHERE A.Key IS NULL OR B.Key IS NULL

加载全部内容

相关教程
猜你喜欢
用户评论