1554979255233.png

代码示例

  1. # 中图:内连接 A∩B
  2. SELECT employee_id,last_name,department_name
  3. FROM employees e JOIN departments d
  4. ON e.`department_id` = d.`department_id`;
  1. # 左上图:左外连接
  2. SELECT employee_id,last_name,department_name
  3. FROM employees e LEFT JOIN departments d
  4. ON e.`department_id` = d.`department_id`;
  1. # 右上图:右外连接
  2. SELECT employee_id,last_name,department_name
  3. FROM employees e RIGHT JOIN departments d
  4. ON e.`department_id` = d.`department_id`;
  1. # 左中图:A - A∩B
  2. SELECT employee_id,last_name,department_name
  3. FROM employees e LEFT JOIN departments d
  4. ON e.`department_id` = d.`department_id`
  5. WHERE d.`department_id` IS NULL
  1. # 右中图:B-A∩B
  2. SELECT employee_id,last_name,department_name
  3. FROM employees e RIGHT JOIN departments d
  4. ON e.`department_id` = d.`department_id`
  5. WHERE e.`department_id` IS NULL
  1. # 左下图:满外连接
  2. # 左中图 + 右上图 A∪B
  3. SELECT employee_id,last_name,department_name
  4. FROM employees e LEFT JOIN departments d
  5. ON e.`department_id` = d.`department_id`
  6. WHERE d.`department_id` IS NULL
  7. UNION ALL # 没有去重操作,效率高
  8. SELECT employee_id,last_name,department_name
  9. FROM employees e RIGHT JOIN departments d
  10. ON e.`department_id` = d.`department_id`;
  1. # 右下图
  2. # 左中图 + 右中图 A∪B - A∩B 或者 (A - A∩B) ∪ (B - A∩B)
  3. SELECT employee_id,last_name,department_name
  4. FROM employees e LEFT JOIN departments d
  5. ON e.`department_id` = d.`department_id`
  6. WHERE d.`department_id` IS NULL
  7. UNION ALL
  8. SELECT employee_id,last_name,department_name
  9. FROM employees e RIGHT JOIN departments d
  10. ON e.`department_id` = d.`department_id`
  11. WHERE e.`department_id` IS NULL

语法格式小结

左中图

  1. # 实现 A - A∩B
  2. select 字段列表
  3. from A left join B
  4. on 关联条件
  5. where 从表关联字段 is null and 等其他子句;

右中图

  1. # 实现 B - A∩B
  2. select 字段列表
  3. from A right join B
  4. on 关联条件
  5. where 从表关联字段 is null and 等其他子句;

左下图

  1. # 实现查询结果是 A∪B
  2. # 用左外的 A,union 右外的 B
  3. select 字段列表
  4. from A left join B
  5. on 关联条件
  6. where 等其他子句
  7. union
  8. select 字段列表
  9. from A right join B
  10. on 关联条件
  11. where 等其他子句;

右下图

  1. # 实现 A∪B - A∩B 或 (A - A∩B) ∪ (B - A∩B)
  2. # 使用左外的 (A - A∩B) union 右外的 (B - A∩B)
  3. select 字段列表
  4. from A left join B
  5. on 关联条件
  6. where 从表关联字段 is null and 等其他子句
  7. union
  8. select 字段列表
  9. from A right join B
  10. on 关联条件
  11. where 从表关联字段 is null and 等其他子句