例子:
create database lianxi
go
use lianxi
go
--创建部门表
create table bumen
(
bmcode int primary key, --部门编号(主键)
bmname varchar(20), --部门名字
bmceo varchar(20), --部门主管
bmtel varchar(20), --部门电话
)
go
--创建人员表
create table renyuan
(
code int primary key identity(1001,1), --员工编号(自增长主键)
name varchar (20), --员工名字
sex varchar (10), --员工性别
age int, --员工年龄
ygbm int, --员工部门(部门表外键)
)
go
--设置好外键关系,之后插入数据
--先插入部门的数据
insert into bumen values(1,'财务部','张三','1111111')
insert into bumen values(2,'人事部','李四','2222222')
insert into bumen values(3,'技术部','王五','3333333')
insert into bumen values(4,'销售部','赵六','4444444')
--插入人员表的信息
insert into renyuan values('张三','男',22,1)
insert into renyuan values('李四','女',32,2)
insert into renyuan values('王五','男',42,3)
insert into renyuan values('赵六','女',52,4)
insert into renyuan values('一','男',28,1)
insert into renyuan values('二','女',38,2)
insert into renyuan values('三','男',48,3)
insert into renyuan values('四','女',58,4)
insert into renyuan values('五','男',25,1)
insert into renyuan values('六','女',35,2)
insert into renyuan values('七','男',45,3)
insert into renyuan values('八','女',55,4)
子查询练习:
--1、查询年纪最大的人的部门名称
select bmname from bumen where bmcode=
(select ygbm from renyuan where code=
(select code from renyuan where age=
(select MAX(age) from renyuan)))
--2、按照年龄排序后的前三个人的所有信息
select top 3 *from renyuan order by age
--3、按照年龄排序后的6/7/8名人员的所有信息
select top 3 *from renyuan where code not in
(select top 5 code from renyuan order by age)
order by age
--4、分页查询,要求 一页给显示5条数据
select top 5*from renyuan
select top 5*from renyuan where code not in (select top 5 code from renyuan )
select top 5*from renyuan where code not in (select top 10 code from renyuan )
--5、总共有几页
select CEILING(COUNT(*)/5.0)from renyuan
--6、查询销售部里的年龄大于35岁的人的所有信息
select * from renyuan where code in
(select code from renyuan where age>35 and ygbm=
(select bmcode from bumen where bmname='销售部')
)
--7、查看所有人员信息,将部门编号替代为部门名称
select code , name, sex , age , (select bmname from bumen where bumen.bmcode= renyuan.ygbm)as 部门 from renyuan
--8、将每个人的主管添加上
select code , name, sex , age , (select bmname from bumen where bumen.bmcode= renyuan.ygbm)as 部门,
(select bmceo from bumen where bumen.bmcode= renyuan.ygbm) from renyuan