当前位置:文档之家› Oracle数据库Select函数基本用法

Oracle数据库Select函数基本用法

1、当使用聚集函数时,SELECT中的列不出现在聚集函数中就必须出现在GROUP BY中,否则会出现语法错误;例如下列语句是非法的:
SELECT department_id, COUNT(last_name) FROM employees;
SELECT department_id,job_id,COUNT(last_name)
FROM employees GROUP BY department_id;
2、where部分不能使用聚集函数,例如下面的查询语句是非法的:
SELECT department_id, AVG(salary) FROM employees
WHERE AVG(salary) > 8000 GROUP BY department_id;
3、使用HAVING关键字限制分组查询的结果,当语句含有HAVING时,先分组再执行含有聚集函数的语句,最后执行HAVING语句:
SELECT department_id, MAX(salary) FROM employees
GROUP BY department_id HAVING MAX(salary)>10000 ;
4、分组函数的嵌套,出现两个分组函数嵌套时,必须出现GROUP BY 语句,否则会发生错误,例如:
SELECT MAX(AVG(salary)) FROM employees;
5、自然连接的练习;使用别名进行连接查询减少内存占用,提高查询效率,能区别不同表中的相同列;
NATURAL JOIN 基于不同表中的相同名字的列,当相同名字的列数据类型不同时,就会返回错误信息。

因为表departments、locations中都含有location_id,故可进行如下自然连接查询:
SELECT department_id, department_name,, city
FROM departments NATURAL JOIN locations ;
6、当具有相同名称的列数据类型不同时可使用USING关键字;当用多列同时满足条件时,可使用USING关键字只匹配其中的一列。

不能对USING关键字后的列进行限制,如下列语句是错误的:
SELECT l.city, d.department_name FROM locations l JOIN departments d
USING (location_id) WHERE d.location_id = 1400;
7、ON关键字的练习
SELECT e.employee_id,st_name,e.department_id,d.department_id, d.location_id FROM employees e JOIN departments d ON (e.department_id = d.department_id);
8、使用ON关键字创建Three-Way连接
SELECT employee_id, city, department_name FROM employees e
JOIN departments d ON d.department_id = e.department_id
JOIN locations l ON d.location_id = l.location_id;
9、使用AND/WHERE增加附加条件
SELECT e.employee_id,st_name,e.department_id,d.department_id, d.location_id FROM employees e JOIN departments d
ON (e.department_id = d.department_id) AND e.manager_id = 149 ;
10、自连接的练习
SELECT st_name emp, st_name mgr
FROM employees worker JOIN employees manager
ON (worker.manager_id = manager.employee_id);
11、非等值连接的练习
SELECT st_name, e.salary, j.JOB_TITLE
FROM employees e JOIN jobs j
ON e.salary BETWEEN j.MIN_SALARY AND j.MAX_SALARY;。

相关主题