多个表可以连接起来进行查询。

左右连表

左连接右连接内连接

展示用户信息&部门名称

  1. 主表 left outer join 从表 on 主表.x = 从表.id
  1. select * from info left outer join depart on info.depart_id = depart.id;
  1. select info.id,info.name,info.email,depart.title from info left outer join depart on info.depart_id = depart.id;
  1. 从表 right outer join 主表 on 主表.x = 从表.id
  1. select info.id,info.name,info.email,depart.title from info right outer join depart on info.depart_id = depart.id;

为了更加直接的查看效果,我们分别在 depart 表 和 info 中额外插入一条数据。

  1. insert into depart(title) values("运维");

这样一来主从表就有区别:

  • info主表,就以info数据为主,depart为辅。

    1. select info.id,info.name,info.email,depart.title from info left outer join depart on info.depart_id = depart.id;
  • depart主表,,就以depart数据为主,info为辅。

    1. select info.id,info.name,info.email,depart.title from info right outer join depart on info.depart_id = depart.id;
  1. select * from info left outer join depart on ....
  2. select * from depart left outer join info on ....

简写:select * from depart left join info on ....

  1. -- 内连接: inner join on 条件
  2. select * from info inner join depart on info.depart_id=depart.id;
  3. +----+----------+-------------------+------+-----------+----+--------+
  4. | id | name | email | age | depart_id | id | title |
  5. +----+----------+-------------------+------+-----------+----+--------+
  6. | 1 | mufeng | 598779784@qq.com | 19 | 1 | 1 | 开发 |
  7. | 2 | 于超 | pyyu@live.com | 49 | 1 | 1 | 开发 |
  8. | 3 | deepwind | deepwind@live.com | 9 | 2 | 2 | 运营 |
  9. | 4 | tony | tony@live.com | 29 | 1 | 1 | 开发 |
  10. | 5 | kelly | kelly@live.com | 99 | 3 | 3 | 销售 |
  11. | 6 | james | james@live.com | 49 | 1 | 1 | 开发 |
  12. | 7 | gailun | gailun@live.com | 49 | 1 | 1 | 开发 |
  13. +----+----------+-------------------+------+-----------+----+--------+
  1. 到目前为止SQL执行顺序:
  2. join
  3. on
  4. where
  5. group by
  6. having
  7. select
  8. order by
  9. limit

上下连表

用的少

  1. select id,title from depart
  2. union
  3. select id,name from info;
  4. select id,title from depart
  5. union
  6. select email,name from info;
  7. -- 列数需相同
  1. select id from depart
  2. union
  3. select id from info;
  4. -- 自动去重
  1. select id from depart
  2. union all
  3. select id from info;
  4. -- 保留所有