当前位置:   article > 正文

MySQL全掌握 - 七种JOIN类型详解_mysql list 参数生成表 join

mysql list 参数生成表 join

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

建表

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

初始化数据

七种JOIN

1. A ∩ B

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

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

  1.  SELECT < select_list >
  2.  FROM TableA A
  3.  LEFT JOIN TableB B
  4.  ON A.Key = B.Key

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

  1.  SELECT < select_list >
  2.  FROM TableA A
  3.  RIGHT JOIN TableB B
  4.  ON A.Key = B.Key

 

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

 

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

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

  1.  SELECT < select_list >
  2.  FROM TableA A
  3.  RIGHT JOIN TableB B
  4.  ON A.Key = B.Key
  5.  WHERE A.Key IS NULL

6. A ∪ B

 

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

 

7. A ∪ B - A ∩ B

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

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号