CREATE [UNIQUE] INDEX <索引名> ON <表名>(<列名>[<次序>][,<列名>[<次序>] ]…);
-- 删除索引
DROP INDEX <索引名>;
复制代码
2、例题
【例1】为门生 - 课程数据库中的Student,Course,SC三个表建立索引。
Student表按学号升序建唯一索引
Course表按课程号升序建唯一索引
SC表按学号升序和课程号降序建唯一索引
create unique
index Stusno on Student(Sno);create unique
index Coucno on Course(Cno);create unique
index SCno on SC(Sno ASC, Cno DESC);
复制代码
【例2】删除Student表的Stusname索引
drop index Stusname;
复制代码
五、查询
SELECT [ALL|DISTINCT] <目标列表达式> [<别名>]
[,<目标列表达式>[<别名>]] …
FROM <表名或视图名>[<别名>]
[, <表名或视图名>[<别名>] ] …
[ WHERE <条件表达式> ]
[ GROUP BY <列名> [, <列名>] …
[ HAVING <条件表达式> ] ]
[ ORDER BY <列名> [, <列名>] … [ ASC|DESC ] ];
复制代码
① from 子句 —— 指定查询对象(根本表或视图)
② where 子句:指定查询条件
③ group by 子句:对查询结果按指定列的值分组,该属性列值相等的元组为一个组
④ having 短句:筛选出满意指定条件的组
⑤ order by 子句:对查询结果表按指定列值的升序或降序排序
以下是示例数据库
学生 - 课程数据库
学生表:
Student(Sno,Sname,Ssex,Sage,Sdept)
课程表:
Course(Cno,Cname,Cpno,Ccredit)
学生选课表:
SC(Sno,Cno,Grade)
复制代码
1、单表查询
① 选择表中的若干列
《查询指定列》
【例1】查询全体门生的学号与姓名
select Sno, Sname from Student;
复制代码
【例2】查询全体门生的姓名、学号、地点系
select Sname, Sno, Sdept from Student;
复制代码
《查询全部列》
【例】查询全体门生的具体记录
select Sno,Sname,Ssex,Sage,Sdept from Student;
select * from Student;
复制代码
《查询经过计算的值》
【例】 查全体门生的姓名及其出生年份(列别名)
select Sname, Sage as 2021-Sage from Student;
复制代码
② 选择表中的若干元组
《消除取值重复的行》
在SELECT子句中使用 DISTINCT 短语
数据如下:
Sno Cno Grade
----- --- ----
19001 1 92
19001 2 85
19001 3 88
19002 2 90
19002 3 80
复制代码
查询选修了课程的门生学号
-- 未优化前
select Sno from SC;
selct all Sno from SC;
结果: Sno
19001
19001
19001
19002
19002
-------------------------
-- 优化后
select distinct Sno from SC;
结果: Sno
19001
19002
复制代码
《查询满意条件的元组》
比较大小
=, >, <, >=, <=, != 或 <>, >, !<
复制代码
【例1】查询计算机系全体门生的名单
select Sname from Student where Sdep = 'CS';
复制代码
【例2】查询全部年龄在20岁以下的门生姓名及其年龄
select Sname, Sage from Student where age < 20;
select Sname, Sage from Student where not age >= 20;
复制代码
【例3】查询考试结果有不及格的门生的学号
select distinct Sno from SC where Grade < 60;
复制代码
确定范围
between ... and ...
not between ... and ...
复制代码
【例1】查询年龄在20~23岁(包罗20岁和23岁)之间的门生的姓名、系别和年龄
select Sname, Sdept, Sage from Student where Sage between 20 and 23;
复制代码
【例2】查询年龄不在20~23岁之间的门生姓名、系别和年龄
select Sname, Sdept, Sage from Student where not Sage between 20 and 23;
复制代码
确定聚集
IN <值表>
NOT IN <值表>
复制代码
【例】查询信息系(IS)、数学系(MA)和计算机科学系(CS)门生的姓名和性别
select Sname, Ssex from Student where Sdept in ('IS', 'MA', 'CS');
复制代码
字符串匹配
LIKE 或 NOT LIKE
[NOT] LIKE ‘<匹配串>’ [ESCAPE ‘ <换码字符>’]
复制代码
固定模版字符串
【例】查询学号为95001的门生的具体情况
select * from Student where Sno like '19001';
select * from Student where Sno = '19001';
复制代码
通配符
% —— 代表恣意长度
_ —— 代表单个字符
【例1】查询全部姓刘门生的姓名、学号和性别
select Sname, Sno, Ssex from Student Sname like '刘%';
复制代码
【例2】 查询姓 “欧阳” 且全名为三个汉字的门生的姓名
select Sname from Student where Sname like '欧阳_';
复制代码
【例3】查询名字中第2个字为"阳"字的门生的姓名和学号
select Sname, Sno from Student where like '_阳%';
复制代码
【例4】查询全部不姓刘的门生姓名
select Sname from Student Sname not like '刘%';
复制代码
转义字符(escape短语)
【例】查询DB_Design课程的课程号和学分
select Cno, Ccredit from Course where Cname like 'DB\_Design' escape '\';