主键 子查询

一、主键 primary key

 1 create database dudu
 2 go
 3 use dudu
 4 go 
 5 create table bumen
 6 (
 7    bcode int primary key,  --部门编号--bcode为主键,不能重复,确保唯一性
 8    bname varchar(20),  --部门名字
 9    bzhuguan varchar(20),  --部门主管
10 )
11 create table renyuan
12 (
13 code int primary key identity(1001,1),   --人员编号 --code为主键,不能重复,确保唯一性。identity(1001,1)自增长主键,表示从1001开始,每次增加1,当添加元素时,不用添加此列
14 name varchar(20),  --人员名字
15 age int,  --人员年龄
16 bc int   --人员所属部门编号
17 )

二、子查询(尽可能的用主键作为查询条件

从上面两表(renyuan和bumen)得知,bc和bcode是一样的,可以根据这个条件来设置关系,即设置外键

设置好外键后,添加元素:

1 insert into bumen values(101,'财务部','张三')
2 insert into bumen values(102,'销售部','李四')
3 insert into bumen values(103,'技术部','王五')
4 go
5 insert into renshu values('张三',34,101)
6 insert into renshu values('李四',35,102)
7 insert into renshu values('王五',24,103)
8 insert into renshu values('白居易',33,101)
9 insert into renshu values('李清照',45,102)
10 insert into renshu values('王阳明',27,103)
11 insert into renshu values('孔子',78,101)
12 insert into renshu values('孟子','66,102)
13 insert into renshu values('老子',89,103)

注意:在给renyuan添加时没有加入code,是因为前面有identity(1001,1)。

-查询年纪最大的人的部门名称
select bname from bumen where bcode=
(select bc from renyuan where code=
(select code from renyuan where age=
(select MAX(age) from renyuan)))

 

--查询销售部里的年龄大于35岁的人的所有信息
select * from renyuan where code in (select code from renyuan where age>35)  and select bc from bumen where baname='销售部'

 

--按照年龄排序后的前三个人的所有信息
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

        

--查看所有人员信息,将部门编号替代为部门名称
select code,name,age,(select bname from bumen where bumen.bname=renyuan,bc) as 部门 from renyuan

 

 

完!!

 

posted @ 2016-09-01 23:12  冲天小肥牛  阅读(264)  评论(0编辑  收藏  举报