SQL server(视图)

-- 想知道每个学生对应的成绩
select * from stulnfo a inner join stumarke b
on a.stuNo=b.stuNo;

--想知道李斯文的成绩
select * from stulnfo a inner join stumarke b on 
a.stuno=b.stuno where stuname='李斯文';

---- 视图
-- 是一种结果的封装,是一个的【虚拟】的表
-- 作用: 提供一个已经封装好的共用于查询
create view view_a as select *from stulnfo

-- 查看视图
select * from view_a

-- 创建一个成绩表的视图
create view view_b as
select * from stumarke

-- 创建一个视图: 联表的数据
create view view_c as
select a.*, labexam,writtenexam,examon
from stulnfo a full join stumarke b
on a.stuNo=b.stuNo

-- 想知道每个学生对应的成绩
select * from view_c

-- 想知道李斯文的成绩
select * from view_c where stuname='李斯文'

-- 哪些人没考试
select * from view_c where examon is null

-- 视图中显示的数据: 男女的比列
create view view_d as
select stusex,count(*)as mount
from stulnfo group by stusex

-- 删除视图
drop view view_d

-- 内联
select * from stulnfo a,stumarke b
where a.stuno=b.stuno

-- 查询性张的人: 张x,张xx,张xxx
select * from stulnfo where stuname like '张%'

-- 查询性张的人: 张xx
select * from stulnfo where stuname like '张__'

-- 查询以丽结尾的人: xx丽
select * from stulnfo where stuname like '%丽'

-- 查询名字带秋的人: 秋xx,x秋x,xx秋
select * from stulnfo where stuname like '%秋%'


-- 自连接
-- 省份 -> 市区

-- 区域(省份+城市)
create table regoin(
id varchar(20) primary key,
name varchar(20) not null,
pid varchar (20)not null
);
insert into regoin values('43','湖南省','0')
insert into regoin values('11','北京省','0')
insert into regoin values('98','广东省','0')
insert into regoin values('18','永州市','43')
insert into regoin values('12','怀化市','43')
insert into regoin values('13','常德市','43')
insert into regoin values('15','广州市','11')
insert into regoin values('16','深圳市','11')

-- 查询所有的省份
select * from regoin where pid='0'

-- 查询湖南省下所有的市
select * from regoin where pid=(
select id from regoin where name='湖南省' 
);

-- 联表查询
select * from regoin a,regoin b
where a.id=b.pid

-- 查询每个省份对应的城市的个数
select a.name,count(b.name)
from regoin a full join regoin b
on a.id=b.pid where a.name like '%省%'
group by a.name
posted @ 2022-05-28 18:44  洗洋洋  阅读(55)  评论(0)    收藏  举报