求一SQL语句,有一表是自关联关系,-对多的关系
如表  table_test  包含三列   id(主键),parentId(外键),name,
我想查出四列,除了前面三列外,再加一列isExist判断当前的记录是否存在子数据,也就是关联的数据,有的话显示true,没有显示false,这条SQL怎么来写呢?

解决方案 »

  1.   

    oracle  做个判断吧 
      select  id, parentId, name ,
      case  when  t.parentId=t.id then  'true'
             else  'false'
             end  isExist,
          from table_test t
     
      

  2.   


    select id,parentID,name,decode(nvl(b.id,''),'',false,true) as isExist 
    from table_test a,table_test b
    where a.parentID=b.id(+)
      

  3.   

    我觉得ks_reny的答案应该正确,测测先
      

  4.   


    select  id, parentId, name , 
    case  when  exixts(select * from table_test where parentId=a.id)
    then  'true' 
    else  'false' 
    end  isExist, 
    from table_test a
     
      

  5.   

    先写个性能慢一点的select id,parentID,name, decode(pid, null, 'N', 'Y') isExist from table_test a, (select parentid pid from table_test group by parentid) b where a.id = b.pid(+)
      

  6.   

    不好意思,多了个逗号select  id, parentId, name , 
    case  when  exixts(select * from table_test where parentId=a.id)
    then  'true' 
    else  'false' 
    end  isExist
    from table_test a
      

  7.   


    错了,两个表的话查询字段名不能那么写
    而且,oracle里没有布尔型数据,true及false得加上''符号以字符串储存
      

  8.   

    6楼的答案是正确的,不过我很期待性能高点的语句怎么写select a.id,b.parentID,a.name, 
     case pid
      when null then 'false'
      else 'true' end isExist 
    from table_test a left join (select parentid pid from table_test group by parentid) b on a.id = b.pid
      

  9.   

    select distinct id,parentId,decode(connect_by_isleaf,1,'false',0,'true') from table_test  start with 1=1 connect by prior id=parentId
      

  10.   

    3楼:
    select id,parentID,name,decode(b.id,null,'false','true') as isExist 
    from table_test a,table_test b
    where a.parentID=b.id(+)
    7楼:
    select  id, parentId, name , 
    case  when  exists(select 1 from table_test where parentId=a.id)
    then  'true' 
    else  'false' 
    end  isExist
    from table_test a
    效率差不多,写法比较简洁,其余不用考虑了