資料庫 SQLserver 主外鍵 子查詢

來源:互聯網
上載者:User

標籤:

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‘)
go

select *from bumen

--插入人員表的資訊

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)


select *from renyuan
--delete from bumen
--delete from renyuan

--查詢年紀最大的人的部門名稱
select bmname from bumen where bmcode=
(select ygbm 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 ygbm=
(select bmcode from bumen where bmname=‘銷售部‘)
)

--查看所有人員資訊,將部門編號替代為部門名稱
select code , name, sex , age , (select bmname from bumen where bumen.bmcode= renyuan.ygbm)as 部門 from renyuan

--將每個人的主管添加上
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

資料庫 SQLserver 主外鍵 子查詢

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.