SQL查询与优化.pdf
文本预览下载声明
SQL 查询与优化
SQL查询与优化
2010.2.22 louis
-1-
SQL 查询与优化
目录
第一章 面试题3
第二章 高级查询4
第三章 SQL优化5
第四章 索引9
-2-
SQL 查询与优化
第一章 面试题
有一表table1有两个字段FID,Fno,写一个SQL语句列出该表中一个FID对应多个不同
的Fno的纪录。
类如:
101 1001
101 1001
102 1002
102 1003
103 1004
104 1005
104 1006
105 1007
105 1007
105 1008
结果:
102 1002
102 1003
104 1005
104 1006
105 1007
105 1008
Select*fromtable1wherefid in(
select fid from table1 group by fid having count(distinct fno)1);
删除一张表的重复记录(ID是自增唯一主键,重复记录:其他字段都是一样)
( )
( )
((数据量很大,性能要求很高))
T
T
表名:TT
Id name age
Id name age
IIddnnaammeeaaggee
1louis20
2louis20
3jimmy 30
4louis20
做法一:
Deletefromtwhereidnotin(Selectmin(id)fromtGroupbyname,age);
做法二:
delete from t where id in(Select distinct a2.id from t a1,t a2 where
-3-
SQL 查询与优化
a1.ida2.id and a1.name=a2.name and a1.age=a2.age);
做法三:
deletefromta1wherenotexists(select*
fromta2
wherea1.ida2.idanda1.name=a2.nameanda1.age=a2.age
);
以上三种做法,均可。但是第三种做法的性能最佳。第一种用notin没办法用到索引,第
二种虽然用了索引,但做了两次查询。
第二章高级查询
8.1、随机返回5条记录
8.1、随机返回5条记录
88..11、、随随机机返返回回55条条记记录录
Select* from(selectename,jobfromemporderbydbms_random.value())whererownum=5
8.3、处理空值排序
8.3、处理空值排序
88..33、、处处理理空空值值排排序序
select*fromemporderbycommdescnullslast(first);
8.4、查询跳过表中的偶数行
8.4、查询跳过表中的偶数行
88..44、、查查询询跳跳过过表表中中的的偶
显示全部