七种类型开始之前我们

MySQL七种JOIN类型小结

数据库教程 2021-11-29 12:46:43 35

导读

在开始之前,我们创建两个表用于演示将要介绍的其中JOIN类型。 建表 CREATETABLE`tbl_dept`( `id`INT(11)NOTNULLAUTO_INCREMENT, `deptName`VARCHAR(30)DEFAULTNULL, `locAdd`VARCHAR(40)DEFAULTNULL, PRIMARYKEY(`id`) )ENGINE=INNODBAUTO_INCREMENT=1DE……

  在开始之前,我们创建两个表用于演示将要介绍的其中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;

初始化数据

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

七种JOIN

1. A ∩ B

MySQL七种JOIN类型小结

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

MySQL七种JOIN类型小结

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

MySQL七种JOIN类型小结

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

MySQL七种JOIN类型小结

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

MySQL七种JOIN类型小结

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

MySQL七种JOIN类型小结 

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

 MySQL七种JOIN类型小结

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

MySQL七种JOIN类型小结

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

MySQL七种JOIN类型小结

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

MySQL七种JOIN类型小结

6. A ∪ B

 MySQL七种JOIN类型小结

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

 MySQL七种JOIN类型小结

7. A ∪ B - A ∩ B

MySQL七种JOIN类型小结

 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

MySQL七种JOIN类型小结

1253067 TFnetwork_cn