zoukankan      html  css  js  c++  java
  • 子查询的问题

    今天遇到一个很奇怪的SQL问题,SQL语句如下:

    select top 1 *,(select top 1 Name_CN from  BaseInfo_Setup where PlantNo=@PlantNo and Type='3') as PlantName_CN  from Payment_Apply
        where
        PlantNo=@PlantNo KS01and
        StartMonth=convert(varchar(6),@StartDate,112) and
        VendorCode=@VendorCode

    问题是,实际在BaseInfo_Setup表中是没有PlantNo这个字段的。

    单独执行:select top 1 Name_CN from  BaseInfo_Setup where PlantNo=@PlantNo and Type='3',SQL是会报错,没有字段。

    但是为什么作为子查询可以呢?

    开始大家认为是否是不存在的字段,SQL过滤了。有人建议看看

    select top 1 *,(select top 1 Name_CN from  BaseInfo_Setup where PlantNo1=@PlantNo and Type='3') as PlantName_CN  from Payment_Apply
        where
        PlantNo=@PlantNo KS01and
        StartMonth=convert(varchar(6),@StartDate,112) and
        VendorCode=@VendorCode

    执行后,会出错。

    后来,有人建议,修改为

    select top 1 *,(select top 1 Name_CN from  BaseInfo_Setup  a where a.PlantNo=@PlantNo and a.Type='3') as PlantName_CN  from Payment_Apply
        where
        PlantNo=@PlantNo KS01and
        StartMonth=convert(varchar(6),@StartDate,112) and
        VendorCode=@VendorCode

    这样如大家所希望的那样,语句果然出错了。

    那么只有一个可能了,这个PlantNo是外面表Payment_Apply的字段了。

    看来以后还是应该在子查询里面加上指代的,说不定SQL会哪天会出现奇怪的问题。

  • 相关阅读:
    [CQOI2011]放棋子
    [CF1192B]动态直径
    [CERC2016]凸轮廓线
    19_08_14-19_08_21校内训练 补题
    [模板]线性递推+BM
    19_08_10[校内训练]割图
    [模板]多项式封装(无讲解)
    19_07_11校内训练[字串染色]
    CF990G
    19_07_09校内训练[分组]
  • 原文地址:https://www.cnblogs.com/wonder223/p/2159798.html
Copyright © 2011-2022 走看看