实操环境:SQL Server Management Studio 15.0.18369.0

先建立完整的表:

create database SCT1
use SCT1
create table Student  (S# char(8), Sname char(10), Ssex char(2), Sage integer, D# char(2),Sclass char(6))

insert into Student values ('98030101','张三','男',20,'03','980301')
insert into Student values ('98030102','张四','女',20,'03','980301')
insert into Student values ('98030103','张五','男',19,'03','980301')
insert into Student values ('98040203','王三','男',20,'04','980402')
insert into Student values ('98040203','王四','男',21,'04','980402')
insert into Student values ('98040203','王五','女',19,'04','980402')
select * from Student

Student表:
student

create table Dept(D# char(2),Dname char(10),Dean char(10))
create table Dept(D# char(2),Dname char(10),Dean char(10))
insert into Dept values ('01','机电','李三')
insert into Dept values ('02','能源','李四')
insert into Dept values ('03','计算机','李五')
insert into Dept values ('04','自动控制','李六')
select * from Dept

Dept表(专业)
dept

insert into Teacher values('001','赵三','01',1200.0)
insert into Teacher values('002','赵四','03',1400.0)
insert into Teacher values('003','赵五','03',1000.0)
insert into Teacher values('004','赵六','04',1100.0)
select * from Teacher

teacher

Course表(课程)

create table Course ( C# char(3), Cname char(12), Chours integer, Credit float(1), T# char(3) )
insert into Course values ('001','数据库',40,6,'001')
insert into Course values ('003','数据结构',40,6,'003')
insert into Course values ('004','编译原理',40,6,'001')
insert into Course values ('005','C语言',30,4.5,'003')
insert into Course values ('002','高等数学',80,12,'004')
select * from Course

teacher
SC表(选课)

create table SC  ( S# char(8), C# char(3), Score float(1) )
insert into SC values('98030101','001',92)
insert into SC values('98030101','002',85)
insert into SC values('98030101','003',88)
insert into SC values('98040202','002',90)
insert into SC values('98040202','003',80)
insert into SC values('98040202','001',55)
insert into SC values('98040203','003',56)
insert into SC values('98030102','001',54)
insert into SC values('98030102','002',85)
insert into SC values('98030102','003',48)
select * from SC

teacher

一、普通查询

查询’张三’和’张四’

select * from Student
where Sname = '张三' or Sname ='张四'

二、in 子查询

1、什么时候需要子查询?

  • 集合成员资格
    • 某一元素是否是某一个集合的成员
  • 集合之间的比较
    • 某一个集合是否包含另一个集合等
  • 集合基数的测试

    • 测试集合是否为空
    • 测试集合是否存在重复元组

和python中的in很类似。

2、基础版

select * from Student
where Sname in('张三','张四')

3、嵌套查询

in中的内容也可以是查询得来的:
如:列出选修了001号课程的学生的学号和姓名

select Sname S# from Student
where S# in(select S# from SC where C# = '001')

teacher

谓词查询:
列出没学过赵四老师讲授课程的所有同学的姓名?

可以一步步筛选出赵四老师的所有学生:
1、从Teacher表中找到赵四老师的教师编号 T#
2、根据T# 在SC表中找到所有学生的学号S#

也可以采用谓词逻辑:

Select    SnameFrom  Student
WhereS#   not  in( Select    S#    From  SC, Course  C, Teacher  TWhereT.Tname = '赵四'  and  SC.C# = C.C# and  T.T# = C.T#  )