oracle基本查询用法入门示例

2020-02-20 12:00:23于海丽

嵌套组函数

select max(avg(sal)) from emp group by deptno;

五、多表查询

oracle的连接  sql99的连接
等值连接        cross joins
不等值连接     natural joins
外连接           using clause
自连接           full or two sided outer joins

SELECT table1.column, table2.column
FROM table1,table2
WHERE table1.column1=table2.column2;
--等值连接
select d.dname,e.ename,e.sal from emp e, dept d where e.deptno=d.deptno;

--多连接条件和and操作符
select d.dname,e.ename,e.sal from emp e, dept d where e.deptno=d.deptno and e.deptno=10;

表的别名
1、使用表别名可简化查询
2、使用表名前缀可以提高执行效率
3、如果使用了表的别名,则不能再使用表的真名。

--不等值连接

--查询员工部门名称和工资等级
select d.dname, e.ename, e.sal, s.grade
from emp e, dept d, salgrade s
where e.deptno = d.deptno
and e.sal >= s.losal
and e.sal <= s.hisal;

外连接语法
外连接查询可以查询不满足连接条件的数据。
外连接的符号是(+)

SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column(+) = table2.column;

SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column= table2.column(+) ;
--查询部门人数
select d.dname, d.deptno, count(e.empno)
 from emp e, dept d
 where e.deptno(+) = d.deptno
 group by d.deptno,d.dname;

自连接

--查询员工的上级
select e.ename as "员工", e2.ename as "上级"
 from emp e, emp e2
 where e.empno = e2.mgr;

使用sql:1999语法连接

SELECT table1.column, table2.column
FROM table1
[CROSS JOIN table2] |
[NATURAL JOIN table2] |
[JOIN table2 USING (column_name)] |
[JOIN table2 ON(table1.column_name=table2.column_name)] |
[LEFT|RIGHT|FULL OUTER JOIN table2 ON(table1.column_name=table2.column_name)];

使用cross join连接的表产生叉集,叉集和笛卡尔集是相同的。

select e.ename,d.dname from emp e cross join dept d;

使作natural join自然连接,会以两个表中具有相同名字的列为条件创建等值连接。

select e.ename,d.dname from emp e natural join dept d;

使用using创建连接,用natural join创建等值连接时,可以使用using指定等值连接中需要用到的列。

select e.ename,d.dname from emp e join dept d USING (deptno);

使用on创建连接,可以指定额外的连接条件。

select e.ename,d.dname from emp e join dept d on e.deptno=d.deptno;