1 / 13

SQL 查询(五)

SQL 查询(五). Any 和 All 、连接查询. 一、使用子查询进行批量比较测试. 进行批量比较测试除了要用到 Any 和 All 谓词外,还要使用比较运算符。 1 、使用 Any 运算符进行批量比较测试 通过比较运算符将一个表达式的值与子查询返回的一列值中的每一个进行比较。若某次比较中结果为 Ture 则返回 Ture 。. 例:查询其他籍贯比湖南所有学生年龄都要小的学生的姓名及年龄。 select sname,age from student where bplace<> ‘ 湖南 ’ and

Download Presentation

SQL 查询(五)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. SQL查询(五) Any和All、连接查询

  2. 一、使用子查询进行批量比较测试 • 进行批量比较测试除了要用到Any和All谓词外,还要使用比较运算符。 • 1、使用Any运算符进行批量比较测试 通过比较运算符将一个表达式的值与子查询返回的一列值中的每一个进行比较。若某次比较中结果为Ture则返回Ture。

  3. 例:查询其他籍贯比湖南所有学生年龄都要小的学生的姓名及年龄。例:查询其他籍贯比湖南所有学生年龄都要小的学生的姓名及年龄。 select sname,age from student where bplace<>‘湖南’and age<all(select age from student where bplace='湖南')

  4. 上例用<min代替为: select sname,age from student where bplace<>'湖南'and age<(select min(age) from student where bplace=‘湖南’) 课堂练习:查询其他籍贯比湖南某一学生年龄小的学生的姓名及年龄。

  5. 二、连接查询 • 连接查询的目的是通过加载连接字段条件将多个表连接起来,以便用户从多个表中检索用户所需的数据。 • 连接查询的两大类表示形式: (1)符合SQL标准连接谓词的表示形式。 (2)扩展使用的关键字JION的表示形式。

  6. 1、连接谓词表示 连接谓词中的两个列称为连接字段,他们必须是可比的。 如:select s.*,e.* from student s,enrlls e where s.sno=e.sno

  7. 2、JOIN关键字指定的连接 (1)内连接:按照ON所指定的连接条件合并两个表,返回满足条件的行。 注意: ①在JOIN运算中,连接具有两个相同数据类型的数据,字段名称不必相同。 ②若两个来源表包含名称相同的字段,则在引用这些字段时须冠以表名。

  8. 如: Select enrolls.sno,sname,cno,grade From enrolls inner join student on enrolls.sno=student.sno • 使用JOIN可进行多表连接,连接采用递归形式。如: Select student.sno,sname,cname,grade From student inner join enrolls on enrolls.sno=student.sno join courses on enrolls.cno=courses.cno

  9. (2)外连接: 外连接的结果表不但包含满足连接条件的行,还包括相应表中的所有行。 • ——左外连接 (LEFT JOIN) • ——右外连接(RIGHT JOIN) • ——完全外连接(FULL JOIN)

  10. 左外连接例题: 找出Jiaoxue管理数据库中所有学生的情况及他们选修课程的课程号和成绩,对没有选课的学生也要包括其情况。 select student.sno,sname,cno,grade from student left outerjoin enrolls on student.sno=enrolls.sno 思考:以下写法会有什么结果? from enrolls left outer join student on student.sno=enrolls.sno

  11. 右外连接例题: 找出Jiaoxue管理数据库中所有课程选修及开设情况。 select courses.cno, cname, sno from enrolls right outer join courses on enrolls.cno=courses.cno 思考:以下写法会有什么结果? from courses right outer join enrolls on enrolls.cno=courses.cno

More Related