主外键,子查询
Posted 0等0
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了主外键,子查询相关的知识,希望对你有一定的参考价值。
use lianxi0720
go
create table bumen
(
bcode int primary key,--部门编号
bname varchar(20), --部门名称
bceo varchar(20), --部门负责人
btel varchar(20) --部门电话
)
go
create table renyuan
(
code int primary key identity(10001,1),
name varchar(20),
sex varchar(10),
age int,
bc int
)
go
--设置好外间关系之后来插入数据
--先插入部门的数据
insert into bumen values(1001,‘财务部‘,‘张三‘,‘1234567‘)
insert into bumen values(1002,‘销售部‘,‘李四‘,‘2345678‘)
insert into bumen values(1003,‘人事部‘,‘王五‘,‘3456789‘)
insert into bumen values(1004,‘技术部‘,‘赵六‘,‘4567890‘)
go
select * from bumen
--插入人员表的信息
insert into renyuan values(‘张三‘,‘男‘,33,1001)
insert into renyuan values(‘李四‘,‘女‘,27,1002)
insert into renyuan values(‘王五‘,‘男‘,25,1003)
insert into renyuan values(‘赵六‘,‘女‘,24,1004)
insert into renyuan values(‘王祖蓝‘,‘男‘,38,1001)
insert into renyuan values(‘马蓉‘,‘女‘,33,1002)
insert into renyuan values(‘王宝强‘,‘男‘,36,1003)
insert into renyuan values(‘杨颖‘,‘女‘,28,1004)
insert into renyuan values(‘郑恺‘,‘男‘,29,1001)
insert into renyuan values(‘范冰冰‘,‘女‘,40,1002)
insert into renyuan values(‘张伟‘,‘男‘,30,1003)
insert into renyuan values(‘蔡依林‘,‘女‘,37,1004)
select * from renyuan
--查询年纪最大的人的部门名称
select MAX(age) from renyuan
select bc from renyuan where age=40
select bname from bumen where bcode=1002
--子查询
select bname from bumen where bcode=
(select bc from renyuan where code=
(select code from renyuan where age =
(select max(age) from renyuan ))
)
--按照年龄排序后的前三个人的所有信息
select top 3 * from renyuan order by age
--按照年龄排序后的6/7/8名人员的所有信息
select top 3 * from renyuan where code not in
(select top 5 code from renyuan order by age)
order by age
--分页查询,要求 一页给显示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)
--总共有几页????
select CEILING( COUNT(*)/5.0) from renyuan
--查询销售部里的年龄大于35岁的人的所有信息
select * from renyuan where code in
(select code from renyuan where age>35 and bc=
(select bcode from bumen where bname=‘销售部‘)
)
--查看所有人员信息,将部门编号替代为部门名称
select code , name, sex , age , (select bname from bumen where bumen.bcode= renyuan.bc)as 部门 from renyuan
--将每个人的主管添加上
select code , name, sex , age , (select bname from bumen where bumen.bcode= renyuan.bc)as 部门,
(select bceo from bumen where bumen.bcode= renyuan.bc) from renyuan
以上是关于主外键,子查询的主要内容,如果未能解决你的问题,请参考以下文章