利用SELECT检索数据
1、DISTINCT关键字去重
SELECT distinct(job) from EMP t
- DISTINCT括号里可以有一列或者多列,多列会被当成一个整体对待。
2、ORDER BY 排序
按列 c2 的升序排列
select * from tablename order by c2 asc;
按列 c2 的降序排列
select * from tablename order by c2 desc;
复合排序,先按列 c1 升序排列,再按 c2 降序排列
select * from tablename order by c1 asc, c2 desc;
3、LIKE模糊查询
例1,查询name字段中包含有“明”字的。
select * from table1 where name like '%明%'
例2,查询name字段中以“李”字开头。
select * from table1 where name like '李*'
例3,查询name字段中含有数字的。
select * from table1 where name like '%[0-9]%'
例4,查询name字段中含有小写字母的。
select * from table1 where name like '%[a-z]%'
4、IN查询条件限制在某列表
IN 列表查询
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)
NOT IN列表查询
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)
5、IS NULL空值查询
select * from a where b is null
6、GROUP BY分组查询
- 可以用在WHERE或者From后面。
以下查询可以通过:
select t.job from EMP t group by t.job
以下是错误示范:
select t.job,t.ename from EMP t group by t.job
查询出来的信息,只能是GROUP BY只能是指定的字段或者是分组函数。
- 分组函数:就是对一组中的数据进行处理获取一个结果
Count:统计查询结果有几条记录,如果数据库表的没有数据, count(*)返回的不是 null,而是 0
Select count(*) from dual;
Select avg(comm) from emp;--平均值
Select max(comm) from emp;--最大值
Select min(comm) from emp;--最小值
Select sum(comm) from emp;--总和
--分组列中空值,可使用Nvl()函数强制分组函数处理空值
select avg(nvl(comm, 0)) from emp;
7、HAVING 子句的使用
- 对group by 分组后,再进行条件限制
正确例子:
select t.job from EMP t group by t.job having t.job='CLERK'
错误示范:having后面只能跟着分组函数、或者group by指定的字段
select t.job from EMP t group by t.job having t.deptno>10