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

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

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

常用的两个链接运算符:

1.join   on(左右连接)

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

二、变量

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

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

局部变量:

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

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

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

ed78a638ba9d79cdb2a93ffaf38271de.png

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

38bde351d7eb8c3c7bbe4cf8228b054a.png

运算符:

850688ab1c3463f4812572e074a8dbcf.png

运算符优先级

fc4eb40d74dd697972fd98682b60d587.png

if。。。else。。

912955cbecd6ab3904b7861683dc1850.png

while语句

1665cf07f6457e5242b73b3c7b148f49.png

while if 嵌套

2b676ce719c9ef1718d134adae0477ae.png

17a99b796f26b05ff6f4b579dac92bb2.png

e5cbf62468f9661e4743b3d717b71cf2.png

961ddebeb323a10fe0623af514929fc1.png

48304ba5e6f9fe08f3fa1abda7d326ab.png

--语文成绩最高的学生信息

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值