比如   select aa from tb1 where cc='1' 
      union 
      select bb from tb1 where cc='1'
把两个cc合并为一个,优化代码,该怎么写呢,请指点

解决方案 »

  1.   

    --这个速度快
    select aa from tb1 where cc='1' 
    union 
    select bb from tb1 where cc='1' --这个速度慢
    select * from
    (
      select aa from tb1
      union 
      select bb from tb1
    ) t
    where cc='1' 
      

  2.   

    这个快
    select aa,bb from tb1 where cc='1';
      

  3.   

    请问楼上的,如果是多个表中的字段,能这样吗,我做的它总是提示 无效的标识符select   tb1.aa   from   tb1 ,tb2  where   tb1.cc='1' and tb1.ee=tb2.ee 
    union   
    select   tb1.bb   from   tb1, tb2   where   tb1.cc='1' and tb1.ee=tb2.ee  
    我用的select * from
    {
       select   tb1.aa   from   tb1 ,tb2  
       uinon
       select   tb1.bb   from   tb1 ,tb2     
    }
    where tb1.cc='1' and tb1.ee=tb2.ff  它总是提示 tb2.ff 无效的标识符这是为什么呢
      

  4.   

    select   *   from 

          select       tb1.aa       from       tb1   ,tb2     
          uinon 
          select       tb1.bb       from       tb1   ,tb2           

    where   tb1.cc='1'   and   tb1.ee=tb2.ff     
    分析一下你的这条SQL语句:

          select       tb1.aa       from       tb1   ,tb2     
          uinon 
          select       tb1.bb       from       tb1   ,tb2           

    这两个大括号中的内容在整个SQL语句中,实际上是构建了一个临时的表.但这个临时的表的名称系统默认为FROM子句中的第一个表名,所以你的WHERE子句中的tb1.cc='1'这个子句,系统没有提示找不到标识符,而对于tb2.ff这个标识,系统跟本在构建的临时表中找不到一个名为tb2的临时表.所以,系统给出找不到tb2.ff这个标识.建议在构建新的临时表后,最好能对该临时表给一个新的名称.这样,有助于SQL语句的可读性.也方便查找一些逻辑错误
      

  5.   

    with a as (select   aa,bb   from   tb1   where   cc='1')
    select aa from a
    union 
    select bb from a
      

  6.   

    请问楼上的,如果是多个表中的字段,能这样吗,我做的它总是提示   无效的标识符 select       tb1.aa       from       tb1   ,tb2     where       tb1.cc='1'   and   tb1.ee=tb2.ee   
    union       
    select       tb1.bb       from       tb1,   tb2       where       tb1.cc='1'   and   tb1.ee=tb2.ee     
    我用的 select   *   from 

          select       tb1.aa       from       tb1   ,tb2     
          uinon 
          select       tb1.bb       from       tb1   ,tb2           

    where   tb1.cc='1'   and   tb1.ee=tb2.ff     它总是提示   tb2.ff   无效的标识符 这是为什么呢 --如果要连接表不能这么写.
    select * from 
    (
     select tb1.aa from tb1 ,tb2 where tb1.cc='1' and tb1.ee=tb2.ff 
     uinon all
     select tb1.bb from tb1 ,tb2 where tb1.cc='1' and tb1.ee=tb2.ff