• SQL之子查询


    子查询概念:把一个查询的结果在另一个查询中使用就叫做子查询

    1.子查询作为条件时

    当我们使用子查询作为条件时,若子查询返回值为多个,则会报以下错误:

    "子查询返回的值不止一个。当子查询跟随在 =、!=、<、<=、>、>= 之后,或子查询用作表达式时,这种情况是不允许的。"

    此时我们应该使用范围【in】关键字来解决。

    2.子查询的分类

      a.独立子查询:可以独立来执行的查询语句做子查询使用

      b.相关子查询:子查询使用了父查询中的列

    3.子查询的使用方式

      a.子查询作为条件使用:当父查询需要某个值,就可以用子查询给出。

      b.子查询作为列的值

    select ClassName from MyClass where ClassId=1
    select StudentName,Gender,(select ClassName from MyClass where ClassId=1) from Student where ClassId=1

    我们使用第一行代码作为列值,现在代码为正确的写法,但会有其他两种出错的写法。

    i.

    select StudentName,Gender,(select ClassName from MyClass) from Student where ClassId=1

    由于没有写限定条件,子查询将返回一列多行多个值,会有如下报错:

    j.

    select StudentName,Gender,(select * from MyClass) from Student where ClassId=1

    由于*代表了一行多列值,会有以下报错:

      c.子查询作为结果集

    i.

    使用子查询结果集实现分页:

    select top 3 *from Student--第一页
    select top 3*from Student where StudentId not in(select top 3 StudentId from Student)--第二页

    在这里我们先选择了第一页,一共三条数据,然后使用第一页的结果集作为第二页的查询条件,得出第二页不在这三条结果范围外的前三条结果。

    j.

    我们还可以使用ROW_NUMBER来实现分页效果,此函数为数据集提供一个连续的编号,我们用这些编号来实现分页。

    select *,ROW_NUMBER()over(order by studentid) as id from Student
    select *from(select *,ROW_NUMBER()over(order by studentid) as id from Student) as temp where id>0 and id<=5
    select *from(select *,ROW_NUMBER()over(order by studentid) as id from Student) as temp where id>5 and id<=10
  • 相关阅读:
    Java代码打成jar后 classgetClassLoadergetResource("")返回为null
    springboot-yml内list、map组合写法
    rpc-java 生成代码路径设置
    Git操作 :从一个分支cherry-pick多个commit到其他分支
    使用maven插件生成grpc所需要的Java代码
    'Failed to import pydot. You must `pip install pydot` and install graphviz
    seasonal_decompose plot figsize
    Failed to install 'TwoSampleMR' from GitHub
    prophet Building wheel for fbprophet (setup.py) ... error
    python matplotlib 绘图线条类型和颜色选择
  • 原文地址:https://www.cnblogs.com/rurui/p/6498027.html
Copyright © 2020-2023  润新知