zoukankan      html  css  js  c++  java
  • SQL 数据库 连接查询 变量、if else、while

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

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

    常用的两个链接运算符

    1.join   on(左右连接)

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

    二、变量

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

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

     局部变量:

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

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

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

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

    运算符:

    运算符优先级

    if。。。else。。

    while语句

     while if 嵌套

    --语文成绩最高的学生信息
    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))
    练习
  • 相关阅读:
    linux命令行挂载NTFS文件系统的移动硬盘
    windows 修改鼠标滚轮自然滚动
    spark sql 的metastore 对接 postgresql
    ubuntu 14.04 源码编译postgresql
    spark sql 对接 HDFS
    部署spark 1.3.1 standalong模式
    perl 打开二进制文件,并拷贝内容
    ubuntu 14 安装XML::Simple 模块
    linux 搭建unixODBC ,并对接 PostgreSQL 9.3.4
    sed 删除指定行
  • 原文地址:https://www.cnblogs.com/shadow-wolf/p/6080448.html
Copyright © 2011-2022 走看看