标签:
内连接是查询的重点,也是数据库学习的重点。
待查询的是scott数据库中的三个表:
emp表:
dept表:
salgrade表:
1、select .... from A ,B的用法
--emp是14行8列,dept是5行3列 select * from emp,dept; --输出结果是70行11列
产生的结果是笛卡尔积:
2、select .... from A, B where ...的用法
select * from emp, dept where empno = 7369; --对产生的笛卡尔积用where过滤
3、select ....from A join B on 的用法
select * from emp "E" join dept "D" --join是连接 on 1 = 1; --on是连接条件 on不能省 有join就必须有on
因为连接条件是1 = 1 永远成立,所以输出的结果是70行11列,跟:
select * from emp,dept;
输出的结果一样。
所以:
select * from emp "E" join dept "D" --SQL99标准 on "E".deptno = "D".deptno;
的输出结果是:
它的原理如下(重要):
其实这跟:
select * from emp, dept where emp.deptno = dept.deptno; --SQL92标准
输出的结果是一样的,推荐使用SQL99标准。
例子:
1、把工资大于2000的员工的姓名、部门的名称和工资的等级输出。
--SQL99标准 select "E".ename "员工姓名","E".sal "工资","D".dname "部门名称","S".GRADE "工资等级" from emp "E" join dept "D" on "E".deptno = "D".deptno join salgrade "S" on "E".sal >= "S".losal and "E".sal <= "S".hisal where "E".sal > 2000;
--SQL92标准 select "E".ename "员工姓名","E".sal "工资","D".dname "部门名称","S".GRADE "工资等级" from emp "E",dept "D",salgrade "S" where ("E".deptno = "D".deptno) and ("E".sal >= "S".losal) and ("E".sal <= "S".hisal and "E".sal > 2000);
2、输出姓名中不包含A的所有员工中工资做高的前三名的每个员工的姓名、工资、工资等级和部门名称
select top 3 "E".ename, "E".sal, "S".grade, "D".dname from emp "E" join dept "D" on "E".deptno = "D".deptno join salgrade "S" on "E".sal between "S".LOSAL and "S".HISAL where "E".ename not like ‘%A%‘ order by "E".sal desc;
3、查找每个部门的编号 该部门所有员工的平均工资 平均工资的等级
select "T".deptno, "T".avg_sal "平均工资","S".GRADE "工资等级" from salgrade "S" join ( select deptno, avg(sal) as "avg_sal" from emp group by deptno --临时表,查找出部门编号和员工的平均工资 ) "T" on "T"."avg_sal" between "S".LOSAL and "S".HISAL;
标签:
原文地址:http://www.cnblogs.com/yzy-blogs/p/5793825.html