赞
踩
名称 | 解释 | 命令 |
---|---|---|
DDL(数据定义语言) | 定义管理数据的对象,对应库和表 | CREATE、DROP、ALTER |
DML(数据操作语言) | 操作数据库中数据 | INSERT、UPDATE、DELETE |
DQL(数据查询语言) | 查询数据库中数据 | SELECT |
DCL(数据控制语言) | 数据权限、提交、回滚控制 | GRANT、COMMIT、ROLLBACK |
本文主要涉及查询数据库中数据的操作,即DQL数据操作语言介绍。
概念
SELECT语法
select [all | distinct] {* | table.* | [table.field1 [as alias1][,table.field2 [as alias2] [,...]]]}
from table_name [as table_alias]
[left | right | inner join table_name2] -- 联合查询
[where] -- where条件语句
[group by] -- 分组
[having] -- 过滤
[order by] -- 排序
[limit {[offset,] row_count | row_count_offset}]
distint
as 起别名
select distinct studentno as no, studentname as name from student
主要操作符
操作符 | 描述 |
---|---|
inner join | 返回两张表中匹配的合并记录 |
left join | 返回左表所有记录并合并进来匹配的右表记录 |
right join | 返回右表所有记录并合并进来匹配的左表记录 |
-- 有两张表:student、result。查询参加了考试的同学信息(学号 姓名 科目编号 分数) /** student为左表 result为右表 并不一定每个同学都参加了考试,不能返回student所有记录。 而应该是result表所有记录并合并入匹配的student表中的记录(right join) */ select s.studentno,studentname,subjectno,score from student as s right join result as r on s.studentno = r.studentno -- 有两张表:student、result。查询缺考同学信息(学号 姓名 科目编号 分数) /** student为左表 result为右表 返回student表所有记录并合并入匹配的result表记录(left join) 当某个学生result表中没有匹配记录,对应的分数列值为null */ select s.studentno,studentname,subjectno,score from student as s left join result as r on s.studentno = r.studentno where score is null
检索表中符合条件的记录,由一个或多个表达式组成,结果为真或假
select studentno from student
where studentname = '张三' or studentname like '张_'
like表达式中的通配符: % (代表0到任意个字符) _ (一个字符)
-- 查询不同课程的平均分,最高分,最低分
-- 前提:根据不同的课程进行分组
SELECT subjectname,AVG(studentresult) AS 平均分,MAX(StudentResult) AS 最高分,MIN(StudentResult) AS 最低分
FROM result AS r
INNER JOIN `subject` AS s
ON r.subjectno = s.subjectno
GROUP BY r.subjectno
HAVING 平均分>80;
order by:排序。asc升序,desc降序
limit:分页
-- 三张表:student,result,subject。查询高数的所有考试结果,按照升序排序(学号 姓名 科目名称 成绩),分页,每页显示5条数据
select s.studentno,studentname,subjectname,score
from student as s
inner join result as r
on s.studentno = r.studentno
inner join subject as sub
on r.subjectno = sub.subjectno
where subjectname='高数'
order by score asc
limit 0,5
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。