数据库(连接)

连接:

  为什么需要连接?:因为我们需要的数据在不同的表中

内连接:

  select 列A from 表A inner join 表B on 条件1=条件2

   在内连接中可以省去 inner 

   注:on 必须和join 一起出现  他没有单独存在的意义

外连接:

  left join :左连接 

  right join: 右连接

  full join :全外连接  注:在mysql中 并不支持

自连接:

  select 列名 from 表A jion 表A on 条件

/*内连接:
基本语法:select 列A from 表A inner(inner可以省略) join 表B  on 条件=条件
注:这里的 on 必须和join 一起出现 他没有单独存在的意义
*/
/*查找每一个员工的领导是谁?*/
/*使用join on 内连接查询数据*/
/*select e.eName,e2.eName from emp e JOIN emp e2 on e.mgr=e2.empno*/
/*使用子查询同样可以做到*/
 select e2.eName as 员工,(select e.eName from emp e where e.empno=e2.mgr) as 领导 from emp e2


/*查询每个员工属于哪个部门 并且显示部门的详细信息
员工的信息和部门信息不在一个表中 所以会涉及到两表联查*/
/*首先使用join 查询*/
/*select * from emp e JOIN dept d on e.deptNo=d.deptNo*/
/*然后使用第二种方法 where 查询 不使用 join */
select * from emp e ,dept d where e.deptNo=d.deptNo
/*使用 where 方法查询使用的时间会更少 */

/*外连接:
   left join 左连接 左表有数据而右表没有数据 他还是会显示左表的数据
但是右表数据的位置为null
   right join 右连接 与左连接相反
   full join 全外连接 在mysql种没有此方法
*/
/*使用左连接来查询
select * from emp e left join dept d on e.deptNo=d.deptNo
在右表 dept 位置没有数据的时候显示为 null 但是左表依然会显示*/
/*select * from emp e join dept d on  e.deptNo=d.deptNo
然而 join方法 只要一方为 null 左右数据都不会显示
*/
/*使用右连接来查询
select * from emp e right join dept d on e.deptNo=d.deptNo
在左表 emp 位置没有数据的时候 左表全部数据都为 null 右表数据还是会显示
*/

在数据库中会涉及到多表联查 有两种方法可以使用 ①:join ②:where

使用 inner join 方法:
    select * from 表A join 表B on 条件A=条件B join 表C on 条件C=条件D
   注:查表C 的时候不能写在 表B后面 而是应该 跟在 on 条件以后
使用 left join 方法:
   select * from 表A left join 表B on 条件A=条件B left join 表C on 条件C=条件D
   注:右查询和inner join 差不多 只是 inner join是内查询 而 left join 是外查询
使用  where 方法:
   select * from 表A,表B where 条件A and 条件B

原文地址:https://www.cnblogs.com/chenyangpeng/p/5483294.html