一、连接查询:通过连接运算符可以实现多个表查询。

连接是关系数据库模型的主要特点,也是它区别于其它类型数据库管理系统的一个标志。

常用的两个链接运算符

1.join   on(左右连接)

2.union(上下连接)  注:只有在列的数据类型一致时才能够连接起来

二、变量

 

SQL语言也跟其他编程语言一样,拥有变量、分支、循环等控制语句。

 

SQL语言里面把变量分为局部变量全局变量,全局变量又称系统变量(@@)。

 

 局部变量:

 

使用declare关键字给变量声明,语法非常简单:declare @<变量名> <变量类型>

 

对变量的赋值可以使用set关键字,使用set关键字时对变量的赋值一次只能赋值一个。

 

我们也可以在查询语句里面对这个变量进行赋值。

 

SQL 数据库 连接查询 变量、if else、while

全局变量:又叫做系统变量。

SQL 数据库 连接查询 变量、if else、while

运算符:

SQL 数据库 连接查询 变量、if else、while

运算符优先级

SQL 数据库 连接查询 变量、if else、while

if。。。else。。

SQL 数据库 连接查询 变量、if else、while

while语句

SQL 数据库 连接查询 变量、if else、while

 

 while if 嵌套

SQL 数据库 连接查询 变量、if else、while

SQL 数据库 连接查询 变量、if else、while

SQL 数据库 连接查询 变量、if else、while

 

SQL 数据库 连接查询 变量、if else、while
--语文成绩最高的学生信息
select * from stu where scode=(select code from score where yu=(select max(yu) from score))
select *from stu where scode=(select top 1 code from score order by yu desc)
--数学成绩最低的学生的任课老师的所有信息
select * from tch where tcode=(select shujiao from stu where scode=(select code from score where shu=(select min(shu) from score)))
--查询汇总成一个表:各门课分数、学生姓名、班级、任课老师的姓名
select stu.sname,banji,score.yu,shu,ying,
(select tname from tch where tcode=stu.yujiao) 语文老师,
(select tname from tch where tcode=stu.shujiao)数学老师,
(select tname from tch where tcode=stu.yingjiao)英语老师
from stu join score on stu.scode=score.code
print @@version
select yu,
case yu
when 99 then '优秀'
when 88 then '良好'
else '合格'
end
from score
go
--查询每个班里数学最高分
select banji,max(shu) from stu join score on  stu.scode=score.code group by banji
--查询语文平均分最高的班级的老师的信息
select * from tch where tcode=
(select top 1 yujiao from stu where banji=
(select top 1 banji from stu join score on stu.scode=score.code group by banji order by avg(yu) desc))

相关文章:

  • 2021-11-23
  • 2022-12-23
  • 2021-12-09
  • 2021-08-09
  • 2021-06-06
  • 2021-11-29
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-11-04
  • 2022-02-13
  • 2022-12-23
  • 2021-12-14
相关资源
相似解决方案