SQL数据查询

来源:互联网 发布:如何查看淘宝客服分流 编辑:程序博客网 时间:2024/06/06 14:26

创建索引,大多数情况下,会提高查询速度


创建索引:

create table temp2(id int(10) not null auto_increment ,title varchar(10) not null, content varchar(10) not null,primary key (`id`),index(title,content)) engine = MYISAM;

alter table temp2 add index title (title);

create index title on temp2(title);

删除索引

  drop index title on temp2;

查看索引

  show index from temp2;

创建索引适用于查询较多,而更新数据不多的情况,因为创建索引也需要时间。

group by子句

可以将查询结果按某一列或多列的值分组,值相等的列为一组。

比如,选出各个课程号及选此课的人数,select cno , count(sno) from course group by cno;
cno在course表中表示课程编号,sno表示学生编号。

查询选修了三门课以上的学生的学号。

select sno from sc group by sno having count(cno)>3;

sno在sc中表示选课的学生学号,cno表示选课的课程编号。

查询平均成绩大于等于90分的学生学号和平均成绩。

select sno,avg(score) from sc group by sno having avg(score)>=90;

嵌套查询

1)带有 in 谓词的查询

在SQL语言中,一个select-from-where 语句成为一个查询块,将一个查询块嵌套在另一个查询块的where或having语句中,称为嵌套查询。

比如选出所有选了二号课的学生姓名,不用连接表,便可以:select sname from student where sno in  (select sno from sc where cno='2');

2)带有比较运算符的子查询

若是已知子查询的结果只有一个,则可以使用比较运算符 =,<,>,>=,<=,。

选出所有学生的比他自己选修课程平均成绩高的科目。

select sname from sc a where score> (select avg(score) from sc b  where a.sno=b.sno);   

自己嵌套自己,便要为表起一个别名,直接在表后加个空格,直接跟别名就好。

3)带有ANY(SOME)或ALL谓词的子查询。  >ANY大于子查询的某个值,>ALL大于子查询全部值。

查询非计算机专业中比任意一个计算机专业的学生年纪小的人的姓名。

select sname from student where dep<>"cs"  and  sage < ANY(select sage from student where dep="cs");

4)存在量词EXISTS

EXISTS谓词的子查询不返回任何数据,只产生逻辑值 true 或  false,查询结果为空返回false,反之返回true

选择选修了1号课的学生姓名。

select sname from student where EXISTS( select * from sc where sc.sno=student.id and sc.cno='1'   );

与之相对的是NOT EXISTS谓词,返回结果与EXIST相反。

5)集合查询

并UNION,交INTERSECT,差EXCEPT,注:参加集合操作的各查询必须列数相同,并且数据类型相同

选出所有计算机学院学生及年龄不大于19岁的学生。

select * from student where dep='cs'  UNION select * from student where  age<=19;

选出既选修1号课又选2号课的学生

select sno from sc where cno='1'  intersect select sno from sc where cno='2' ;

6)基于派生表的查询

子查询不仅可以出现在where从句中,还可以出现在from后面的从句。

比如查询每个学生比自己平均成绩高的科目。

select sno,cno from sc , (select sno,avg(score) from sc group by sno  ) as tavg(avg_sno,avg_score) where  tage.avg_sno=student.sno and sc.socre>tavg.avg_core   ;





0 0