Dear All:
     请教大家一个问题。分少诚意多,呵呵。表tab1 和 tab2
1、如果tab2有记录,则查询出tab1中存在于tab2的记录:
select a.* from tab1  a
where exists(select b.col1 from tab2 b where b.col1 = a.col1);2、如果tab2为空,则查询出tabl的全表: select a.* from tab1 a希望能用一条sql实现,不想用 (if 判断和动态sql 来实现。
小弟不甚感激!

解决方案 »

  1.   

    select a.* from tab1 a
    where exists
    (select b.col1 from tab2 b 
    where b.col1 = a.col1);--当tab2不为空时,union前面就是你要的结果 union后面为空
    union
    select a.* from tab1 a,(selec count(*) cn from tab2) t
    where cn=0--当tab2为空时,union前面查询结果为空,后面就是整个tab1表
      

  2.   


    多谢!如果想换成删除的话,union 好像不可以吧。
    delete from tab1 where exists(select ... from tab2);
      

  3.   

    select * from t1 where 1= decode(select count(*) from t2),0,1,0) or exists select 1 from t2 where t1.col=t2.col);
      

  4.   

    select a.* from tab1 a
    where exists(select b.col1 from tab2 b where b.col1 = a.col1)
    or (select count(1) from tab2)=0;
      

  5.   


    create table t1(col int,ss varchar(20));create table T2
    (
      COL INTEGER,
      SS  VARCHAR2(20),
      AA  VARCHAR2(10)
    )insert into t1 values(1,'adasd');
    insert into t1 values(2,'fasfasga');
    insert into t1 values(2,'fasfasga');insert into t2 values(1,'adasd','fasfa');
    insert into t2 values(2,'hthfhfgh','asfasffa');
    select *
      from t1
     where 1 = decode ((select count(*) from t2), 0, 1, 0)  ---如果count(*)=0 ,t2为空,那么1=1 条件成立,查出T1所有记录,否则按or后的条件得出结果
        or exists  (select 1 from t2 where t1.col = t2.col);
      

  6.   

    狂狼仔看来是名人啦 呵呵。
    结贴散分啦。
    看来这种问题对大家来说太容易了。
    下次我给个10分,应该就够了吧 呵呵。
    大家可怜可怜我们这个穷 CSDNer吧 。