笛卡尔积查询:(没有意义)
语法:
* 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);