在进行数据操作之前,首先需要有几张完整的表。建立两张表,分别为tableA和tableB
create table tableA(id integer,name varchar(25),age number);insert into tableA values('101','Jack','25');insert into tableA values('102','mike','22');insert into tableA values('103','amy','23');
create table tableB(id integer,class number,grade number);
insert into tableB values('101','3','1');
insert into tableB values('104','4','2');
insert into tableB values('105','3','2');
结果如下:
1、 查询空字段
首先在tableA加一条ID为空的记录,如下图所示
查询空字段(null)
select * from 表名 where 字段名 is null;select * from tableA where id is null;
如上图所示,ID为空的那条记录被查询出来了。
2、ORDER BY 语句
ORDER BY 语句用于根据指定的列对结果集进行排序。
ORDER BY 语句默认按照升序对记录进行排序。
如果希望按照降序对记录进行排序,可以使用 DESC 关键字。
如果希望按照升序对记录进行排序,可以使用 ASC 关键字。
select * from 表名 order by 字段名 DESC/ASC;select * from tableA order by age desc;
select * from tableA order by age asc;
3、 过滤重复记录(distinct)
首先在tableA的age字段加一条重复的记录
insert into tableA values('105','john','25');目前在age字段中有两个’25’,现在使用过滤查询函数,将重复的记录过滤掉
Select distinct 字段名 from 表名;select distinct age from tableA;
4、 模糊查询
%在前表示以关键字结尾,%在后表示以关键字开头,两边都有%表示关键字在中间。
SELECT * FROM 表名 where 字段名 LIKE ‘XX%’;
SELECT * FROM 表名 where 字段名 LIKE ‘%XX’;
SELECT * FROM 表名 where 字段名 LIKE ‘%XX%’;SELECT * FROM tableA where name LIKE 'Ja%';
SELECT * FROM tableA where name LIKE '%ck';
SELECT * FROM tableA where name LIKE '%ac%';
5、SQL函数
Count统计字段记录个数
Select count(字段名) from 表名;select count (age) from tableA;Sum求和
Select sum(字段名) from 表名;select sum (age) from tableA;max求最大值
Select max(字段名) from 表名;select max (age) from tableA;min求最小值
Select min(字段名) from 表名;select min (age) from tableA;avg求平均值
Select avg(字段名) from 表名;select avg (age) from tableA;
为了便于理解,现在将两张表画出来
tableA
ID
Name
Age
101
Jack
25
102
mike
22
103
amy
23
105
john
25
tableB
ID
Class
Grade
101
3
1
104
4
2
105
3
2
6、两张表有一个字段名相同的字段ID,查询两张表哪些ID是相同的
select a.字段名,b.字段名 from 表名A a,表名B b where a.字段名=b.字段名;select a. id,b. id from tableA a, tableB b where a. id =b. id;
从上图可以看出在tableA和tableB中,ID 101和105是相同的。
以上语句可以通过变换查询条件获得不同的查询结果。
7、子查询 IN() 或者 NOT IN() ,又叫嵌套查询
现在要查询ID为101和103的记录,有以下两种查询方式
SELECT * FROM tableA WHERE id IN( 101,103 );
或 SELECT * FROM tableA WHERE id=101 OR id=103;
两条语句的查询结果是一样的。
8、根据关键字查询
显示所有年龄为25岁的人:
SELECT * FROM tableA WHERE name IN( SELECT name FROM tableA where age=25);
做一个分解步骤来理解,
第一先步骤先执行 SELECT name FROM tableA where age=25;
第二步 , 在执行 SELECT * FROM tableA WHERE name IN( 第一步的结果 );
显示所有年龄不为25岁的人:
SELECT * FROM tableA WHERE name NOT IN( SELECT name FROM tableA where age=25);
9、Decode分类函数
计算出年龄为25岁的人数之和,显示的求和字段名为n_25
SELECT SUM(DECODE(age,25,1,0)) n_25 FROM tableA;
其中sum是求和函数。decode是分类函数,用于查找年龄为25岁的人,n_25为求和字段名。查询结果显示年龄为25岁的人数为2个。