外连接 内链接 子查询

图五 内连接和外连接的区别

 

笛卡尔积查询:(没有意义)

语法:

* select * from A,B;

* 笛卡尔积的查询的结果不是想要的结果!!!

内连接查询

语法:

* select * from A inner join B on 条件; --- inner 可以省略!!!

* select * from A join B on 条件;

案例:

* select * from dept join emp on dept.did = emp.dno;

等价于

* select * from dept,emp where dept.did = emp.dno;---隐式内连接

外连接查询
左外连接查询

语法:

* select * from A left outer join B on 条件; ---outer 可以省略

* select * from A left join B on 条件;

案例:

* select * from dept left outer join emp on dept.did = emp.dno;

右外连接查询

语法:

* select * from A right outer join B on 条件;---outer可以省略

* select * from A right join B on 条件;

案例:

* select * from dept right outer join emp on dept.did = emp.dno;

子查询:

子查询:一个sql的查询的结果需要依赖另一个sql的查询结果!

创建表:

create table exam(

id int primary key auto_increment,

name varchar(20),

math int,

english int

);

insert into exam values (null,'aaa',59,61);

insert into exam values (null,'bbb',62,81);

insert into exam values (null,'ccc',73,73);

insert into exam values (null,'ddd',84,64);

insert into exam values (null,'eee',91,58);

insert into exam values (null,'fff',69,92);

insert into exam values (null,'ggg',75,83);

* 查询数学成绩在数学平均分之上的同学信息:

* 求数学的平均分:select avg(math) from exam;

* 求数学分数大于平均分:select * from exam where math > 平均分;

* 平均分是一条sql的查询结果.

* select * from exam where math > (select avg(math) from exam);

在子查询中可以使用关键字any、all.

* any:任意的

* > any :select * from exam where english > any (select math from exam);

* any:任意一个值.最小的那个可以了.

* < any :select * from exam where english < any (select math from exam);

* any:任意一个值.最大的那个值比较就可以了.

* all:所有的

* > all :select * from exam where english > all (select math from exam);

* < all :select * from exam where english < all (select math from exam);

* 多表的查询:

* 按照部门名称统计人员的个数!

* select d.dname,count(*) from dept d,emp e where d.did = e.dno group by d.dname;

* 统计每个部门平均工资!

* select d.dname,avg(eprice) from dept d,emp e where d.did = e.dno group by d.dname;

* 查询哪些员工的工资大于任意部门平均工资:

* select * from emp where eprice > any (select avg(eprice) from dept d,emp e where d.did = e.dno group by d.dname);

* 查询哪些员工的工资大于所有部门平均工资:

* select * from emp where eprice > all (select avg(eprice) from dept d,emp e where d.did = e.dno group by d.dname);

转载于:https://my.oschina.net/jiemoxiaodi/blog/848243

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值