java开发数据库学习路线

一、数据库的多表查询

  1. 分类

合并结果集  union  union all

连接查询

内连接

外连接

左外

右外

自然连接

子查询

  1. 合并结果集,就是把2个select语句的查询结果合并到一起

要求被合并的2个结果,列数和列的类型必须一致

select * from a union select id,name from b;

select * from a union all select id,name from b;

  1. 连接查询(***)

连接查询就是求多个表的乘积,a和b表,连接查询的结果就是a*b

select * from stuj,score;

可以使用主外键关系等式 来去除无用信息

连接查询会产生笛卡尔积

select * from stuj,score where stuj.id=score.id;

  1. 内链接:上面的语句是内链接语句,但不是标准方式

sql标准内链接:

select * from stuj inner join score on stuj.id=score.id;

特点:查询结果必然是满足等式条件

  1. 外链接

特点:查询结果可能会出现不满足条件的可能性

左外:以左边的表为主表

select * from stuj as s left outer join score c on s.id = c.id;

select * from score as s left outer join stuj c on s.id = c.id;

右外:以右边的表为主表

  1. 自然连接

不需要给出主外键关系等式,会自动找到

select * from score natural join stuj;

  1. 子查询(****)

一个select语句中包含另一个select语句

也叫嵌套查询

特点:

  根据子查询的位置:

where 后 : 条件

from 后 : 做表

当子查询出现在where后,可以使用如下关键字

      any

   all

子查询的结果形式

      单行单列:条件

   单行多列:条件

   多行单列:条件

多行多列:表

--查询工资高于xiaosan的人的信息

--查询xiaosan的工资

select salary from emp where name=’xiaosan’;

select * from emp where salary>( select salary from emp where name=’xiaosan’);

--查询工资高于大于1号部门所有人的人的信息

--1号部门最大工资

select max(salary) from emp where deptid=1;

--查询编号为1002的人的名字,工资,部门和部门地址

select name,salary,deptid from emp e where id=1002;

select e.name,e.salary,e.deptid,d.address from emp e,dept d

where e.deptid = d.deptid and id=1002;

select e.name,e.salary,e.deptid,d.address from (select id,salary,deptid from emp) e,dept d where e.deptid = d.deptid and id=1002;

  1. 自连接  自己连接自己

--查询编号为1004的人的姓名以及领导编号和领导姓名

select e1.id,e1.name,e2.id,e2.name from emp e1,emp e2

where e1.leader = e2.id and e1.id=1004;

猜你喜欢

转载自www.cnblogs.com/PersianCat/p/11087815.html