索引
建立索引:
create (unique) index 索引名 on 表名(列名);
unique:带上表示唯一索引。
用alter创建索引:
创建一个主索引,索引值唯一,且不能为NULL
alter table 表名 add primary key(列名);
创建一个唯一索引
alter table 表名 add unique ( index 索引名 ) (列名);
(index 索引名) 可省略。
创建一个普通索引
alter table 表名 add index 索引名 (列名);
删除索引
drop index 索引名 on 表名;
alter table 表名 drop index 索引名;
删除主键索引:alter table 表名 drop primary key
eg: 删除student表的hehe索引
drop inedx hehe on student;
或 alter table student drop index hehe;
数据查询
单表查询
eg :查询选修了两门以上课程的学生学号
select sno from sc grounp by sno having count(*)>2;
查询表中的若干元组
确定集合 : in( ) , not in( )
eg:查询在 cs, ma,is系中学生的姓名和性别
select sname,ssex from student where sdept in(‘cs’ ,‘ma’ ,‘is’);
或者 select sname,ssex from student where sdept =‘cs’ or sdept=‘ma’ or sdept=‘is’;
eg:查询不在 cs, ma,is系中学生的姓名和性别
select sname,ssex from student where sdept not in(‘cs’ ,‘ma’ ,‘is’);
连接查询:同时涉及两个以上的表的查询
1. 等值(=)与非等值连接查询
eg :查询每个学生及其选修课程的情况(student表和sc表)
自然排序:在等值连接中把目标列中重复的属性列去掉
eg :查询学生201215012选修课程的总学分
select sum(ccredit) from sc,course where sno=‘201215012’ and sc.cno=course.cno;
eg:查询选修2号课程且成绩在90分以上的所有学生的学号和姓名
select student.sno,sname from student,sc where student.sno=sc.sno and sc.cno=‘2’ and sc.grade>90;
2. 自身查询:一个表与其自己进行连接
需要起别名进行区别,并且由于所有的属性名都是同名属性,因此必须使用别名前缀
eg:查询每一门课的间接先修课(先修课的先修课)
嵌套查询
带有exists的查询
eg:查询所有选修了1号课程的学生姓名
eg: 查询没有选修了1号课程的学生姓名
一些带exists或not exists的子查询不能被其他形式的子查询等价替换,但是带in,any,all,比较运算符的查询都可以用带exists等价替换。
eg:查询与刘晨在同一个系学习的学生
eg:查询选修了全部课程的学生姓名
eg:查询非计算机科学系中比计算机科学系任意一个学生年龄大的学生姓名
集合查询
参加集合操作的查询结果列数必须相同,对应项的数据类型也必须相同
union并操作
eg:查询计算机科学系的学生 及 年龄不大于20岁的学生
eg: 查询选修了课程1或者课程2的学生
交集运算和差集运算mysql都不支持。