一、30条优化建议
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 ‘%李%’若要提高效率,可以考虑全文检索。
7. 如果在 where 子句中使用参数,也会导致全表扫描。因为SQL只有在运行时才会解析局部变量,但优化程序不能将访问计划的选择推迟到运行时;它必须在编译时进行选择。然 而,如果在编译时建立访问计划,变量的值还是未知的,因而无法作为索引选择的输入项。如下面语句将进行全表扫描:select id from t where num=@num可以改为强制查询使用索引:select id from t with(index(索引名)) where 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 name like ‘abc%’
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.尽量避免向客户端返回大数据量,若数据量过大,应该考虑相应需求是否合理。
二、45条经典查询案例
#学生表
CREATE TABLE STUDENT
(SNO VARCHAR(3) NOT NULL,
SNAME VARCHAR(4) NOT NULL,
SSEX VARCHAR(2) NOT NULL,
SBIRTHDAY DATETIME,
CLASS VARCHAR(5))ENGINE=MyISAM AUTO_INCREMENT=348 DEFAULT CHARSET=utf8 ;
#课程表
CREATE TABLE COURSE
(CNO VARCHAR(5) NOT NULL,
CNAME VARCHAR(10) NOT NULL,
TNO VARCHAR(10) NOT NULL)ENGINE=MyISAM AUTO_INCREMENT=348 DEFAULT CHARSET=utf8 ;
#成绩表
CREATE TABLE SCORE
(SNO VARCHAR(3) NOT NULL,
CNO VARCHAR(5) NOT NULL,
DEGREE NUMERIC(10, 1) NOT NULL)ENGINE=MyISAM AUTO_INCREMENT=348 DEFAULT CHARSET=utf8 ;
#教师表
CREATE TABLE TEACHER
(TNO VARCHAR(3) NOT NULL,
TNAME VARCHAR(4) NOT NULL, TSEX VARCHAR(2) NOT NULL,
TBIRTHDAY DATETIME NOT NULL,
PROF VARCHAR(6),
DEPART VARCHAR(10) NOT NULL)ENGINE=MyISAM AUTO_INCREMENT=348 DEFAULT CHARSET=utf8 ;
INSERT INTO STUDENT (SNO,SNAME,SSEX,SBIRTHDAY,CLASS) VALUES (108 ,'曾华'
,'男' ,'1977-09-01',95033);INSERT INTO STUDENT (SNO,SNAME,SSEX,SBIRTHDAY,CLASS) VALUES (105 ,'匡明'
,'男' ,'1975-10-02',95031);INSERT INTO STUDENT (SNO,SNAME,SSEX,SBIRTHDAY,CLASS) VALUES (107 ,'王丽'
,'女' ,'1976-01-23',95033);INSERT INTO STUDENT (SNO,SNAME,SSEX,SBIRTHDAY,CLASS) VALUES (101 ,'李军'
,'男' ,'1976-02-20',95033);INSERT INTO STUDENT (SNO,SNAME,SSEX,SBIRTHDAY,CLASS) VALUES (109 ,'王芳'
,'女' ,'1975-02-10',95031);INSERT INTO STUDENT (SNO,SNAME,SSEX,SBIRTHDAY,CLASS) VALUES (103 ,'陆君'
,'男' ,'1974-06-03',95031);
INSERT INTO COURSE(CNO,CNAME,TNO)VALUES ('3-105' ,'计算机导论',825);INSERT INTO COURSE(CNO,CNAME,TNO)VALUES ('3-245' ,'操作系统' ,804);INSERT INTO COURSE(CNO,CNAME,TNO)VALUES ('6-166' ,'数据电路' ,856);INSERT INTO COURSE(CNO,CNAME,TNO)VALUES ('9-888' ,'高等数学' ,100);
INSERT INTO SCORE(SNO,CNO,DEGREE)VALUES (103,'3-245',86);INSERT INTO SCORE(SNO,CNO,DEGREE)VALUES (105,'3-245',75);INSERT INTO SCORE(SNO,CNO,DEGREE)VALUES (109,'3-245',68);INSERT INTO SCORE(SNO,CNO,DEGREE)VALUES (103,'3-105',92);INSERT INTO SCORE(SNO,CNO,DEGREE)VALUES (105,'3-105',88);INSERT INTO SCORE(SNO,CNO,DEGREE)VALUES (109,'3-105',76);INSERT INTO SCORE(SNO,CNO,DEGREE)VALUES (101,'3-105',64);INSERT INTO SCORE(SNO,CNO,DEGREE)VALUES (107,'3-105',91);INSERT INTO SCORE(SNO,CNO,DEGREE)VALUES (108,'3-105',78);INSERT INTO SCORE(SNO,CNO,DEGREE)VALUES (101,'6-166',85);INSERT INTO SCORE(SNO,CNO,DEGREE)VALUES (107,'6-106',79);INSERT INTO SCORE(SNO,CNO,DEGREE)VALUES (108,'6-166',81);
INSERT INTO TEACHER(TNO,TNAME,TSEX,TBIRTHDAY,PROF,DEPART)
VALUES (804,'李诚','男','1958-12-02','副教授','计算机系');INSERT INTO TEACHER(TNO,TNAME,TSEX,TBIRTHDAY,PROF,DEPART)
VALUES (856,'张旭','男','1969-03-12','讲师','电子工程系');INSERT INTO TEACHER(TNO,TNAME,TSEX,TBIRTHDAY,PROF,DEPART)
VALUES (825,'王萍','女','1972-05-05','助教','计算机系');INSERT INTO TEACHER(TNO,TNAME,TSEX,TBIRTHDAY,PROF,DEPART)
VALUES (831,'刘冰','女','1977-08-14','助教','电子工程系');
#####################################################
#我是华丽丽的分割线
#####################################################
#1、 查询Student表中的所有记录的Sname、Ssex和Class列。
SELECT sname,ssex,class from student;
#2、 查询教师所有的单位即不重复的Depart列。
SELECT DISTINCT depart from teacher;
#3、 查询Student表的所有记录。
SELECT * from student;
#4、 查询Score表中成绩在60到80之间的所有记录。
SELECT * from score WHERE degree BETWEEN 60 and 80;SELECT * from score WHERE degree >= 60 and degree <=80;
#5、 查询Score表中成绩为85,86或88的记录。
SELECT * from score WHERE degree in(85,86,88);SELECT * from score WHERE degree = 85 or degree = 86 or degree = 88;
#6、 查询Student表中“95031”班或性别为“女”的同学记录。
SELECT * from student WHERE class= '95031' or ssex = '女';
#7、 以Class降序查询Student表的所有记录。
SELECT * from student ORDER BY class desc;
#8、 以Cno升序、Degree降序查询Score表的所有记录。
SELECT * from score ORDER BY cno asc, degree DESC;
#9、 查询“95031”班的学生人数。
SELECT COUNT(class) as 95031班的学生人数 from student WHERE class = '95031';
#10、查询Score表中的最高分的学生学号和课程号。
SELECT sno,cno from score WHERE degree = (SELECT MAX(degree) from score);
#11、查询‘3-105’号课程的平均分。
SELECT avg(degree) 平均分 from score GROUP BY cno HAVING cno = '3-105';
#12、查询Score表中至少有5名学生选修的并以3开头的课程的平均分数。
SELECT cno ,avg(degree) 平均分 from score GROUP BY cno HAVING COUNT(*) >=5 and cno like '3%';
#13、查询最低分大于70,最高分小于90的Sno列。
SELECT sno from score GROUP BY sno HAVING MIN(degree)>70 and MAX(degree) < 90;
#14、查询所有学生的Sname、Cno和Degree列。
SELECT sname,cno,degree from student as stu INNER JOIN score as s on stu.sno = s.sno;
#15、查询所有学生的Sno、Cname和Degree列。
SELECT s.sno,cname,degree from student stu INNER JOIN score s INNER JOIN course c on stu.sno = s.sno and c.cno = s.cno;
#16、查询所有学生的Sname、Cname和Degree列。
SELECT sname,cname,degree from student stu INNER JOIN score s INNER JOIN course c on stu.sno = s.sno and c.cno = s.cno;
#17、查询“95033”班所选课程的平均分。
#子查询实现
SELECT cno , avg(degree) 平均分 from score WHERE sno in (SELECT sno from student WHERE class = '95033') GROUP BY cno;
#连接查询实现
SELECT cno , avg(degree) 平均分 from student stu INNER JOIN score s on stu.sno = s.sno and class = '95033' GROUP BY cno;
#18、假设使用如下命令建立了一个grade表:
create table grade(low decimal(3,0),upp decimal(3,0),rank char(1));insert into grade values(90,100,'A');insert into grade values(80,89,'B');insert into grade values(70,79,'C');insert into grade values(60,69,'D');insert into grade values(0,59,'E');
#现查询所有同学的Sno、Cno和rank列。
SELECT s.sno,c.cno,degree,rank from student stu INNER JOIN score s INNER JOIN course c INNER JOIN grade on stu.sno = s.sno and c.cno = s.cno and degree>= grade.low and degree<=grade.upp;
#19、查询选修“3-105”课程的成绩高于“109”号同学成绩的所有同学的记录。
SELECT * from student WHERE sno in (SELECT sno from score WHERE degree > (SELECT degree from score WHERE sno='109' and cno='3-105') and cno='3-105');SELECT stu.* from student as stu INNER JOIN score as s on stu.sno = s.sno and cno='3-105' and degree > (SELECT degree from score WHERE sno='109' and cno='3-105') ;
#20、查询score中选学一门以上课程的同学中分数为非最高分成绩的记录。
SELECT score.* from score INNER JOIN (SELECT sno ,MAX(degree) as maxdegree from score GROUP BY sno HAVING COUNT(*) >1) temp on score.sno = temp.sno and score.degree < temp.maxdegree;
#21、查询成绩高于学号为“109”、课程号为“3-105”的成绩的所有记录。
SELECT s.* from student as stu INNER JOIN score as s on stu.sno = s.sno and cno='3-105' and degree > (SELECT degree from score WHERE sno='109' and cno='3-105') ;
#22、查询和学号为107的同学同年出生的所有学生的Sno、Sname和Sbirthday列。
SELECT sno ,sname,sbirthday from student WHERE year(sbirthday) = (SELECT year(sbirthday) from student WHERE sno='107');
#23、查询“张旭“教师任课的学生成绩。
SELECT * from score WHERE cno in (SELECT cno from course WHERE tno = (SELECT tno from teacher WHERE tname ='张旭'));
#24、查询选修某课程的同学人数多于5人的教师姓名。
SELECT tname from teacher WHERE tno in (SELECT tno from course WHERE cno in (SELECT cno from score GROUP BY cno HAVING COUNT(*)>5));
#25、查询95033班和95031班全体学生的记录。
SELECT * from student WHERE CLASS = '95033' or CLASS = '95031';
#26、查询存在有85分以上成绩的课程Cno.
SELECT cno from score GROUP BY cno HAVING MAX(degree) >= 85;
#27、查询出“计算机系“教师所教课程的成绩表。
SELECT * from score WHERE cno in (SELECT CNO from course WHERE TNO in (SELECT tno from teacher WHERE DEPART = '计算机系'));
#28、查询“计算机系”与“电子工程系“不同职称的教师的Tname和Prof。
SELECT tname ,prof from teacher WHERE DEPART = '计算机系' and prof not in (SELECT prof from teacher WHERE DEPART = '电子工程系')
UNIONSELECT tname ,prof from teacher WHERE DEPART = '电子工程系' and prof not in (SELECT prof from teacher WHERE DEPART = '计算机系');
#29、查询选修编号为“3-105“课程且成绩至少高于选修编号为“3-245”的同学的Cno、Sno和Degree,并按Degree从高到低次序排序。
SELECT sno, cno ,degree from score WHERE CNO = '3-105' and DEGREE > ANY(SELECT DEGREE from score WHERE CNO = '3-245') ORDER BY degree desc;SELECT sno, cno ,degree from score WHERE CNO = '3-105' and DEGREE > (SELECT MIN(DEGREE) from score WHERE CNO = '3-245') ORDER BY degree desc;
#30、查询选修编号为“3-105”且成绩高于选修编号为“3-245”课程的同学的Cno、Sno和Degree.
SELECT sno, cno ,degree from score WHERE CNO = '3-105' and DEGREE > ALL(SELECT DEGREE from score WHERE CNO = '3-245') ORDER BY degree desc;SELECT sno, cno ,degree from score WHERE CNO = '3-105' and DEGREE > (SELECT MAX(DEGREE) from score WHERE CNO = '3-245') ORDER BY degree desc;
#31、查询所有教师和同学的name、sex和birthday.
SELECT sname as name , ssex as sex , sbirthday as birthday from student
UNION ALL #万一老师和学生姓名 性别 出生日相同呢 所以加了ALLSELECT tname , tsex , tbirthday as birthday from teacher;
#32、查询所有“女”教师和“女”同学的name、sex和birthday.
SELECT sname as name , ssex as sex , sbirthday as birthday from student WHERE ssex = '女'UNION ALL
SELECT tname , tsex , tbirthday as birthday from teacher WHERE tsex = '女';
#33、查询成绩比该课程平均成绩低的同学的成绩表。
SELECT sno, cno as score_cno ,degree from score WHERE DEGREE < (SELECT avg(DEGREE) FROM score GROUP BY CNO HAVING CNO = score_cno );
SELECT A.* from score as A INNER JOIN (SELECT cno , avg(DEGREE) as avgdegree FROM score GROUP BY CNO) as B on A.cno = B.cno and A.DEGREE < B.avgdegree;
#34、查询所有任课教师的Tname和Depart.
SELECT tname,depart from teacher WHERE TNO in (SELECT tno from course);
#35、查询所有未讲课的教师的Tname和Depart.
SELECT tname,depart from teacher WHERE TNO not in (SELECT tno from course);
#36、查询至少有2名男生的班号。
SELECT class from student GROUP BY class HAVING COUNT(class)>1;
#37、查询Student表中不姓“王”的同学记录。
SELECT * from student WHERE sname not like '王%';
#38、查询Student表中每个学生的姓名和年龄。
SELECT sname ,TIMESTAMPDIFF(YEAR,sbirthday,NOW()) as age from student;
#39、查询Student表中最大和最小的Sbirthday日期;。
SELECT MAX(sbirthday),MIN(sbirthday) from student ;
#40、以班号和年龄从大到小的顺序查询Student表中的全部记录。
SELECT * from student ORDER BY class desc,sbirthday desc;
#41、查询“男”教师及其所上的课程。
SELECT * from course WHERE TNO in (SELECT TNO from teacher WHERE TSEX = '男');
#42、查询最高分同学的Sno、Cno和Degree列。
SELECT stu.sno,s.cno,s.degree from student stu INNER JOIN score s on stu.sno=s.sno and s.degree = (select max(degree) from score);
#43、查询和“李军”同性别的所有同学的Sname.
SELECT sname from student WHERE ssex = (SELECT ssex from student where sname='李军');
#44、查询和“李军”同性别并同班的同学Sname.
SELECT sname from student WHERE ssex = (SELECT ssex from student where sname='李军') and class = (SELECT class from student where sname='李军');
#45、查询所有选修“计算机导论”课程的“男”同学的成绩表
SELECT score.* from student INNER JOIN score INNER JOIN course on student.SNO = score.SNO AND score.CNO = course.CNO AND course.CNAME = '计算机导论' AND student.SSEX = '男';