有时候数据不在一张表中,需要使用到其他表的数据,这时候就需要用到表的,连接,并,笛卡尔乘积

内连接查询

内连接的主要意思是:它保存的是符合连接条件的字段而去除不符合条件的字段。

连接的关键字是 join on ,连接条件写在 on 子句中

内连接分类:

  • 自然连接:— 相对其他连接两种自然连接会去除重复字段
  • 等值连接 — 就是连接条件是 = 语法是inner join on ,包括自连接
  • 不等连接 — 就是在关键词后面使用 = 以外的如 > < 等等运算符来连接

自连接

自连接就是一张表自己通过一些条件连接自己,语法是 inner join in

本文中的所有例子基于:想象的company数据库中的employee表

  1. select e.employeename,e.job,l.loadername from employee e
  2. inner join employee l on e.id = l.empno

不同的表之间的等值连接也是这样的使用

不等连接

> , < , <= , >= , !=

  1. select e.job,l.name from employee e
  2. inner join employee l on e.id != l.empno

外连接

外连接的主要意思是:它会将不满足条件的数据也返回

  • 左外连 left join
  • 右外连 right join
  • 全外连

子查询

子查询很重要,子查询就是在where的后面在跟上一个 select 语句来获得一个新的返回值,然后就可以通过一些逻辑运算符来进行判断,以获得我们需要的数据

  1. seleect * from user
  2. where id = (select id from olduser where name = 'xxx')


也可以通过多个字段来进行筛选

  1. select * from employee where(sal,job) = (select sal,job from t_employee where name = 'smith')

带exists的子查询