zoukankan      html  css  js  c++  java
  • 避免使用select * 的最特别的理由

    快速搜索Google或Bing,你会无数的文章会告诉你数据库中显示使用“ SELECT *”是一件可怕的事情。你的代码将更加脆弱。这对你的数据字典不利。使用后,你最终会遇到冲突等等。你可以从Markus Winand的文章(https://use-the-index-luke.com/blog/2013-08/its-not-about-the-star-stupid)中找到更合理的论点,但最终在大多数情况下,潜在的弊端超过了使用SELECT *带来的任何便利好处。

    (我之所以说“大多数”,是因为PL/SQL是少数几种语言之一,它的%ROWTYPE语法和DML的VALUES/SET ROW子句可以使你避免很多风险。这也是PL/SQL为什么如此酷的一个原因)。

    但是,这可能是你会想避免选择SELECT *的最奇怪的原因。我将从一个简单的表T开始,并命名为CHILD和PARENT列,因为我将使用递归子查询因子分解功能来查询该表:

    SQL> create table t(child,parent ) as select 2,1 from dual;
    
    Table created.
    

    由于只有一行数据,从递归查询得到的结果并不是特别令人兴奋

    SQL> with recursive(chd,par) as (
      2  select child,parent
      3  from t
      4  union all
      5  select t.child,t.parent
      6  from t,recursive
      7  where recursive.chd=t.parent
      8  )
      9  select *
     10  from recursive;
    
           CHD        PAR
    ---------- ----------
             2          1
    

    这里要注意的关键是第2行和第5行。正如你对任何UNION ALL查询所期望的那样,UNION ALL第一部分中的列数必须与UNION ALL第二部分中的列数相匹配。

    在第5行中,我查询表T中的CHILD和PARENT列,精明的读者已经发现,这是T中的所有列,并且与表的定义中的顺序相同。因此,让我们看看当我违背传统观点并将其替换为SELECT *时会发生什么。

    SQL> with recursive (chd,par) as (
      2     select child,parent
      3     from t
      4     union all
      5     select t.*
      6     from t, recursive
      7     where recursive.chd = t.parent
      8     )
      9     select *
     10     from recursive;
            select t.*
            *
    ERROR at line 5:
    ORA-01789: query block has incorrect number of result columns
    

    要了解为什么会这样,我们需要仔细查看递归子查询分解的文档,其中指出:

    “The number of column aliases following WITH query_name and the number of columns in the SELECT lists of the anchor and recursive query blocks must be the same.”
    

      

    ORA-01789错误提示此检查是在语法处理的早期完成的,然后将星号扩展为列。因此,在UNION ALL的第二部分上只有一个项(早期表示即在将星号扩展成列名之前,这样只是将星号当成了一个列了,因此不匹配)。通过在SQL中添加乱码,可以进一步了解此检查的早期假设。

    SQL> with recursive (chd,par) as (
      2    select child,parent
      3    from t
      4    union all
      5    select blahblahblah.*
      6    from t, recursive
      7    where recursive.chd = t.parent
      8  )
      9  select *
     10  from recursive;
      select blahblahblah.*
      *
    ERROR at line 5:
    ORA-01789: query block has incorrect number of result columns
    

    即使引用了不存在的“ blahblahblah”,我们得到的第一个错误也不是引用不存在,而是列数。该语句在到达数据字典进行进一步验证之前,未通过第一次语法检查。

    因此,当涉及到递归查询子处理时,请确保将这些列列出来!

    原文地址:https://connor-mcdonald.com/2020/10/12/the-weirdest-reason-to-avoid-select/

  • 相关阅读:
    Vue:Vue CLI 3的学习
    npm:基础
    Spring Boot:@Value和@ConfigurationProperties
    Spring Boot:引入依赖时何时不指定版本号
    数据库事物的四大特性及隔离级别
    Python之xml文档及配置文件处理(ElementTree模块、ConfigParser模块)
    Python之数据序列化(json、pickle、shelve)
    Python之文件与目录操作(os、zipfile、tarfile、shutil)
    Python之日期与时间处理模块(date和datetime)
    Python之列表生成式、生成器、可迭代对象与迭代器
  • 原文地址:https://www.cnblogs.com/abclife/p/13819303.html
Copyright © 2011-2022 走看看