高级查询在数据库中用得是最频繁的,也是应用最普遍的。html
Ø 基本经常使用查询mysql
--select
select * from student;
--all 查询全部
select all sex from student;
--distinct 过滤重复
select distinct sex from student;
--count 统计
select count(*) from student;
select count(sex) from student;
select count(distinct sex) from student;
--top 取前N条记录
select top 3 * from student;
--alias column name 列重命名
select id as 编号, name '名称', sex 性别 from student;
--alias table name 表重命名
select id, name, s.id, s.name from student s;
--column 列运算
select (age + id) col from student;
select s.name + '-' + c.name from classes c, student s where s.cid = c.id;
--where 条件
select * from student where id = 2;
select * from student where id > 7;
select * from student where id < 3;
select * from student where id <> 3;
select * from student where id >= 3;
select * from student where id <= 5;
select * from student where id !> 3;
select * from student where id !< 5;
--and 而且
select * from student where id > 2 and sex = 1;
--or 或者
select * from student where id = 2 or sex = 1;
--between ... and ... 至关于而且
select * from student where id between 2 and 5;
select * from student where id not between 2 and 5;
--like 模糊查询
select * from student where name like '%a%';
select * from student where name like '%[a][o]%';
select * from student where name not like '%a%';
select * from student where name like 'ja%';
select * from student where name not like '%[j,n]%';
select * from student where name like '%[j,n,a]%';
select * from student where name like '%[^ja,as,on]%';
select * from student where name like '%[ja_on]%';
--in 子查询
select * from student where id in (1, 2);
--not in 不在其中
select * from student where id not in (1, 2);
--is null 是空
select * from student where age is null;
--is not null 不为空
select * from student where age is not null;
--order by 排序
select * from student order by name;
select * from student order by name desc;
select * from student order by name asc;
--group by 分组
按照年龄进行分组统计
select count(age), age from student group by age;
按照性别进行分组统计
select count(*), sex from student group by sex;
按照年龄和性别组合分组统计,并排序
select count(*), sex from student group by sex, age order by age;
按照性别分组,而且是id大于2的记录最后按照性别排序
select count(*), sex from student where id > 2 group by sex order by sex;
查询id大于2的数据,并完成运算后的结果进行分组和排序
select count(*), (sex * id) new from student where id > 2 group by sex * id order bysex * id;
--group by all 全部分组
按照年龄分组,是全部的年龄
select count(*), age from student group by all age;
--having 分组过滤条件
按照年龄分组,过滤年龄为空的数据,而且统计分组的条数和现实年龄信息
select count(*), age from student group by age having age is not null;
按照年龄和cid组合分组,过滤条件是cid大于1的记录
select count(*), cid, sex from student group by cid, sex having cid > 1;
按照年龄分组,过滤条件是分组后的记录条数大于等于2
select count(*), age from student group by age having count(age) >= 2;
按照cid和性别组合分组,过滤条件是cid大于1,cid的最大值大于2
select count(*), cid, sex from student group by cid, sex having cid > 1 and max(cid) > 2;
Ø 嵌套子查询程序员
子查询是一个嵌套在select、insert、update或delete语句或其余子查询中的查询。任何容许使用表达式的地方均可以使用子查询。子查询也称为内部查询或内部选择,而包含子查询的语句也成为外部查询或外部选择。web
# from (select … table)示例正则表达式
将一个table的查询结果当作一个新表进行查询
select * from (
select id, name from student where sex = 1
) t where t.id > 2;
上面括号中的语句,就是子查询语句(内部查询)。在外面的是外部查询,其中外部查询能够包含如下语句:sql
一、 包含常规选择列表组件的常规select查询数据库
二、 包含一个或多个表或视图名称的常规from语句性能优化
三、 可选的where子句并发
四、 可选的group by子句函数
五、 可选的having子句
# 示例
查询班级信息,统计班级学生人生
select *, (select count(*) from student where cid = classes.id) as num
from classes order by num;
# in, not in子句查询示例
查询班级id大于小于的这些班级的学生信息
select * from student where cid in (
select id from classes where id > 2 and id < 4
);
查询不是班的学生信息
select * from student where cid not in (
select id from classes where name = '2班'
)
in、not in 后面的子句返回的结果必须是一列,这一列的结果将会做为查询条件对应前面的条件。如cid对应子句的id;
# exists和not exists子句查询示例
查询存在班级id为的学生信息
select * from student where exists (
select * from classes where id = student.cid and id = 3
);
查询没有分配班级的学生信息
select * from student where not exists (
select * from classes where id = student.cid
);
exists和not exists查询须要内部查询和外部查询进行一个关联的条件,若是没有这个条件将是查询到的全部信息。如:id等于student.id;
# some、any、all子句查询示例
查询班级的学生年龄大于班级的学生的年龄的信息
select * from student where cid = 5 and age > all (
select age from student where cid = 3
);
select * from student where cid = 5 and age > any (
select age from student where cid = 3
);
select * from student where cid = 5 and age > some (
select age from student where cid = 3
);
Ø 聚合查询
一、 distinct去掉重复数据
select distinct sex from student;
select count(sex), count(distinct sex) from student;
二、 compute和compute by汇总查询
对年龄大于的进行汇总
select age from student
where age > 20 order by age compute sum(age) by age;
对年龄大于的按照性别进行分组汇总年龄信息
select id, sex, age from student
where age > 20 order by sex, age compute sum(age) by sex;
按照年龄分组汇总
select age from student
where age > 20 order by age, id compute sum(age);
按照年龄分组,年龄汇总,id找最大值
select id, age from student
where age > 20 order by age compute sum(age), max(id);
compute进行汇总前面是查询的结果,后面一条结果集就是汇总的信息。compute子句中能够添加多个汇总表达式,能够添加的信息以下:
a、 可选by关键字。它是每一列计算指定的行聚合
b、 行聚合函数名称。包括sum、avg、min、max、count等
c、 要对其执行聚合函数的列
compute by适合作先分组后汇总的业务。compute by后面的列必定要是order by中出现的列。
三、 cube汇总
cube汇总和compute效果相似,但语法较简洁,并且返回的是一个结果集。
select count(*), sex from student group by sex with cube;
select count(*), age, sum(age) from student where age is not null group by age withcube;
cube要结合group by语句完成分组汇总
Ø 排序函数
排序在不少地方须要用到,须要对查询结果进行排序而且给出序号。好比:
一、 对某张表进行排序,序号须要递增不重复的
二、 对学生的成绩进行排序,得出名次,名次能够并列,但名次的序号是连续递增的
三、 在某些排序的状况下,须要跳空序号,虽然是并列
基本语法
排序函数 over([分组语句] 排序子句[desc][asc])
排序子句 order by 列名, 列名
分组子句 partition by 分组列, 分组列
# row_number函数
根据排序子句给出递增连续序号
按照名称排序的顺序递增
select s.id, s.name, cid, c.name, row_number() over(order by c.name) as number
from student s, classes c where cid = c.id;
# rank函数函数
根据排序子句给出递增的序号,可是存在并列而且跳空
顺序递增
select id, name, rank() over(order by cid) as rank from student;
跳过相同递增
select s.id, s.name, cid, c.name, rank() over(order by c.name) as rank
from student s, classes c where cid = c.id;
# dense_rank函数
根据排序子句给出递增的序号,可是存在并列不跳空
不跳过,直接递增
select s.id, s.name, cid, c.name, dense_rank() over(order by c.name) as dense
from student s, classes c where cid = c.id;
# partition by分组子句
能够完成对分组的数据进行增长排序,partition by能够与以上三个函数联合使用。
利用partition by按照班级名称分组,学生id排序
select s.id, s.name, cid, c.name, row_number() over(partition by c.name order by s.id) as rank
from student s, classes c where cid = c.id;
select s.id, s.name, cid, c.name, rank() over(partition by c.name order by s.id) asrank
from student s, classes c where cid = c.id;
select s.id, s.name, cid, c.name, dense_rank() over(partition by c.name order by s.id) as rank
from student s, classes c where cid = c.id;
# ntile平均排序函数
将要排序的数据进行平分,而后按照等分排序。ntile中的参数表明分红多少等分。
select s.id, s.name, cid, c.name,
ntile(5) over(order by c.name) as ntile
from student s, classes c where cid = c.id;
Ø 集合运算
操做两组查询结果,进行交集、并集、减集运算
一、 union和union all进行并集运算
--union 并集、不重复
select id, name from student where name like 'ja%'
union
select id, name from student where id = 4;
--并集、重复
select * from student where name like 'ja%'
union all
select * from student;
二、 intersect进行交集运算
--交集(相同部分)
select * from student where name like 'ja%'
intersect
select * from student;
三、 except进行减集运算
--减集(除相同部分)
select * from student where name like 'ja%'
except
select * from student where name like 'jas%';
Ø 公式表表达式
查询表的时候,有时候中间表须要重复使用,这些子查询被重复查询调用,不但效率低,并且可读性低,不利于理解。那么公式表表达式能够解决这个问题。
咱们能够将公式表表达式(CET)视为临时结果集,在select、insert、update、delete或是create view语句的执行范围内进行定义。
--表达式
with statNum(id, num) as
(
select cid, count(*)
from student
where id > 0
group by cid
)
select id, num from statNum order by id;
with statNum(id, num) as
(
select cid, count(*)
from student
where id > 0
group by cid
)
select max(id), avg(num) from statNum;
Ø 链接查询
一、 简化链接查询
--简化联接查询
select s.id, s.name, c.id, c.name from student s, classes c where s.cid = c.id;
二、 left join左链接
--左链接
select s.id, s.name, c.id, c.name from student s left join classes c on s.cid = c.id;
三、 right join右链接
--右链接
select s.id, s.name, c.id, c.name from student s right join classes c on s.cid = c.id;
四、 inner join内链接
--内链接
select s.id, s.name, c.id, c.name from student s inner join classes c on s.cid = c.id;
--inner能够省略
select s.id, s.name, c.id, c.name from student s join classes c on s.cid = c.id;
一、 聚合函数
max最大值、min最小值、count统计、avg平均值、sum求和、var求方差
select
max(age) max_age,
min(age) min_age,
count(age) count_age,
avg(age) avg_age,
sum(age) sum_age,
var(age) var_age
from student;
二、 日期时间函数
select dateAdd(day, 3, getDate());--加天
select dateAdd(year, 3, getDate());--加年
select dateAdd(hour, 3, getDate());--加小时
--返回跨两个指定日期的日期边界数和时间边界数
select dateDiff(day, '2011-06-20', getDate());
--相差秒数
select dateDiff(second, '2011-06-22 11:00:00', getDate());
--相差小时数
select dateDiff(hour, '2011-06-22 10:00:00', getDate());
select dateName(month, getDate());--当前月份
select dateName(minute, getDate());--当前分钟
select dateName(weekday, getDate());--当前星期
select datePart(month, getDate());--当前月份
select datePart(weekday, getDate());--当前星期
select datePart(second, getDate());--当前秒数
select day(getDate());--返回当前日期天数
select day('2011-06-30');--返回当前日期天数
select month(getDate());--返回当前日期月份
select month('2011-11-10');
select year(getDate());--返回当前日期年份
select year('2010-11-10');
select getDate();--当前系统日期
select getUTCDate();--utc日期
作管理系统的,不管是bs结构的仍是cs结构的,都不可避免的涉及到数据库表结构的设计,sql语句的编写等。所以在开发系统的时候,表结构设计是否合理,sql语句是否标准,写出的sql性能是否优化每每会成为公司衡量程序员技术水平的标准。
咱们程序员不是dba,不须要时刻关注sql运行时间,千方百计优化表结构,存储空间,优化表读取速度等等,可是在开发系统时,时刻保持优良的写sql语句的做风是颇有必要的,这关乎到我的在公司的声誉,嘿嘿,你懂的。。。
新来的程序员老鸟,在一个开发团队中,须要表现一下本身的水平,奠基在公司的地位,须要努力表现一把,最简单的从写的sql语句就很容易表现出来,曾经就有一次,一个老程序员,上面定位是要作团队领导的,先历练一下作个制单的模块,列表sql中有一列这位老鸟直接写了个select语句从别的表中取之,而不是用表之间关联获得,一下破坏本身程序员老鸟光辉形象。
作技术的仍是要注重本身的内涵,提高内功,哈哈。
闲话少说,总结一点程序员老鸟写sql顺手拈来的功夫吧:
1. 不论一个sql中涉及到多个表,每次都用两个表(结果集)操做,获得新的结果后,再和下一个表(结果集)操做。
2. 避免在select f1,(select f2 from tableB ).... from tableA 这样获得字段列。直接用tableA和tableB关联获得A.f1,B.f2就能够了。
3.避免隐含的类型转换
如
select id from employee where emp_id='8' (错)
select id from employee where emp_id=8 (对)
emp_id是整数型,用'8'会默认启动类型转换,增长查询的开销。
4. 尽可能减小使用正则表达式,尽可能不使用通配符。
5. 使用关键字代替函数
如:
select id from employee where UPPER(dept) like 'TECH_DB' (错)
select id from employee where SUBSTR(dept,1,4)='TECH' (错)
select id from employee where dept like 'TECH%' (对)
6.不要在字段上用转换函数,尽可能在常量上用
如:
select id from employee where to_char(create_date,'yyyy-mm-dd')='2012-10-31' (错)
select id from employee where create_date=to_date('2012-10-31','yyyy-mm-dd') (对)
7.不使用联接作查询
如:select id from employee where first_name || last_name like 'Jo%' (错)
8. 尽可能避免先后都用通配符
如:
select id from employee where dept like '%TECH%' (错)
select id from employee where dept like 'TECH%' (对)
9. 判断条件顺序
如:
select id from employee where creat_date-30>to_date('2012-10-31','yyyy-mm-dd') (错)
select id from employee where creat_date >to_date('2012-10-31','yyyy-mm-dd')+30 (对)
10. 尽可能使用exists而非in
固然这个也要根据记录的状况来定用exists仍是用in, 一般的状况是用exists
select id from employee where salary in (select salary from emp_level where....) (错)
select id from employee where salary exists(select 'X' from emp_level where ....) (对)
11. 使用not exists 而非not in
和上面的相似
12. 减小查询表的记录数范围
13.正确使用索引
索引能够提升速度,通常来讲,选择度越高,索引的效率越高。
14. 索引类型
惟一索引,对于查询用到的字段,尽量使用惟一索引。
还有一些其余类型,如位图索引,在性别字段,只有男女的字段上用。
15. 在常常进行链接,可是没有指定为外键的列上创建索引
16. 在频繁进行排序会分组的列上创建索引,如常常作group by 或 order by 操做的字段。
17. 在条件表达式中常常用到的不一样值较多的列上创建检索,在不一样值少的列上不创建索引。如性别列上只有男,女两个不一样的值,就不必创建索引(或创建位图索引)。若是创建索引不但不会提升查询效率,反而会严重下降更新速度。
18. 在值比较少的字段作order by时,翻页会出现记录紊乱问题,要带上id字段一块儿作order by.
19. 不要使用空字符串进行查询
如:
select id from employee where emp_name like '%%' (错)
20. 尽可能对常常用做group by的关键字段作索引。
21. 正确使用表关联
利用外链接替换效率十分低下的not in运算,大大提升运行速度。
如:
select a.id from employee a where a.emp_no not in (select emp_no from employee1 where job ='SALE') (错)
22. 使用临时表
在必要的状况下,为减小读取次数,可使用通过索引的临时表加快速度。
如:
select e.id from employee e ,dept d where e.dept_id=d.id and e.empno>1000 order by e.id (错)
select id,empno from employee into temp_empl where empno>1000 order by id
select m.id from temp_emp1 m,dept d where m.empno=d.id (对)
对于大数据量sql语句性能优化更多的工做就交给dba去实践,咱们程序员作好这些基本功就行了。
以上文章来着博客园web报表的博客。
1.对查询进行优化,应尽可能避免全表扫描,首先应考虑在 where 及 order by 涉及的列上创建索引。
2.应尽可能避免在 where 子句中对字段进行 null 值判断,不然将致使引擎放弃使用索引而进行全表扫描,如:
select id from t where num is null
能够在num上设置默认值0,确保表中num列没有null值,而后这样查询:
select id from t where num=0
3.应尽可能避免在 where 子句中使用!=或<>操做符,不然将引擎放弃使用索引而进行全表扫描。
4.应尽可能避免在 where 子句中使用 or 来链接条件,不然将致使引擎放弃使用索引而进行全表扫描,如:
select id from t where num=10 or num=20
能够这样查询:
select id from t where num=10
union all
select id from t where num=20
5.in 和 not in 也要慎用,不然会致使全表扫描,如:
select id from t where num in(1,2,3)
对于连续的数值,能用 between 就不要用 in 了:
select id from t where num between 1 and 3
6.下面的查询也将致使全表扫描:
select id from t where name like '%abc%'
若要提升效率,能够考虑全文检索。
7.若是在 where 子句中使用参数,也会致使全表扫描。由于SQL只有在运行时才会解析局部变量,但优化程序不能将访问计划的选择推迟到运行时;它必须在编译时进行选择。然而,若是在编译时创建访问计划,变量的值仍是未知的,于是没法做为索引选择的输入项。以下面语句将进行全表扫描:
select id from t where num=@num <mailto:num=@num>
能够改成强制查询使用索引:
select id from t with(index(索引名)) where num=@num <mailto:num=@num>
8.应尽可能避免在 where 子句中对字段进行表达式操做,这将致使引擎放弃使用索引而进行全表扫描。如:
select id from t where num/2=100
应改成:
select id from t where num=100*2
9.应尽可能避免在where子句中对字段进行函数操做,这将致使引擎放弃使用索引而进行全表扫描。如:
select id from t where substring(name,1,3)='abc'--name以abc开头的id
select id from t where datediff(day,createdate,'2005-11-30')=0--‘2005-11-30’生成的id
应改成:
select id from t where name like 'abc%'
select id from t where createdate>='2005-11-30' and createdate<'2005-12-1'
10.不要在 where 子句中的“=”左边进行函数、算术运算或其余表达式运算,不然系统将可能没法正确使用索引。
11.在使用索引字段做为条件时,若是该索引是复合索引,那么必须使用到该索引中的第一个字段做为条件时才能保证系统使用该索引,不然该索引将不会被使用,而且应尽量的让字段顺序与索引顺序相一致。
12.不要写一些没有意义的查询,如须要生成一个空表结构:
select col1,col2 into #t from t where 1=0
这类代码不会返回任何结果集,可是会消耗系统资源的,应改为这样:
create table #t(...)
13.不少时候用 exists 代替 in 是一个好的选择:
select num from a where num in(select num from b)
用下面的语句替换:
select num from a where exists(select 1 from b where num=a.num)
14.并非全部索引对查询都有效,SQL是根据表中数据来进行查询优化的,当索引列有大量数据重复时,SQL查询可能不会去利用索引,如一表中有字段sex,male、female几乎各一半,那么即便在sex上建了索引也对查询效率起不了做用。
15.索引并非越多越好,索引当然能够提升相应的 select 的效率,但同时也下降了 insert 及 update 的效率,由于 insert 或 update 时有可能会重建索引,因此怎样建索引须要慎重考虑,视具体状况而定。一个表的索引数最好不要超过6个,若太多则应考虑一些不常使用到的列上建的索引是否有必要。
16.应尽量的避免更新 clustered 索引数据列,由于 clustered 索引数据列的顺序就是表记录的物理存储顺序,一旦该列值改变将致使整个表记录的顺序的调整,会耗费至关大的资源。若应用系统须要频繁更新 clustered 索引数据列,那么须要考虑是否应将该索引建为 clustered 索引。
17.尽可能使用数字型字段,若只含数值信息的字段尽可能不要设计为字符型,这会下降查询和链接的性能,并会增长存储开销。这是由于引擎在处理查询和链接时会逐个比较字符串中每个字符,而对于数字型而言只须要比较一次就够了。
18.尽量的使用 varchar/nvarchar 代替 char/nchar ,由于首先变长字段存储空间小,能够节省存储空间,其次对于查询来讲,在一个相对较小的字段内搜索效率显然要高些。
19.任何地方都不要使用 select * from t ,用具体的字段列表代替“*”,不要返回用不到的任何字段。
20.尽可能使用表变量来代替临时表。若是表变量包含大量数据,请注意索引很是有限(只有主键索引)。
21.避免频繁建立和删除临时表,以减小系统表资源的消耗。
22.临时表并非不可以使用,适当地使用它们可使某些例程更有效,例如,当须要重复引用大型表或经常使用表中的某个数据集时。可是,对于一次性事件,最好使用导出表。
23.在新建临时表时,若是一次性插入数据量很大,那么可使用 select into 代替 create table,避免形成大量 log ,以提升速度;若是数据量不大,为了缓和系统表的资源,应先create table,而后insert。
24.若是使用到了临时表,在存储过程的最后务必将全部的临时表显式删除,先 truncate table ,而后 drop table ,这样能够避免系统表的较长时间锁定。
25.尽可能避免使用游标,由于游标的效率较差,若是游标操做的数据超过1万行,那么就应该考虑改写。
26.使用基于游标的方法或临时表方法以前,应先寻找基于集的解决方案来解决问题,基于集的方法一般更有效。
27.与临时表同样,游标并非不可以使用。对小型数据集使用 FAST_FORWARD 游标一般要优于其余逐行处理方法,尤为是在必须引用几个表才能得到所需的数据时。在结果集中包括“合计”的例程一般要比使用游标执行的速度快。若是开发时间容许,基于游标的方法和基于集的方法均可以尝试一下,看哪种方法的效果更好。
28.在全部的存储过程和触发器的开始处设置 SET NOCOUNT ON ,在结束时设置 SET NOCOUNT OFF 。无需在执行存储过程和触发器的每一个语句后向客户端发送 DONE_IN_PROC 消息。
29.尽可能避免大事务操做,提升系统并发能力。
30.尽可能避免向客户端返回大数据量,若数据量过大,应该考虑相应需求是否合理。
两篇文章来源: