oracle  例如:一张表tb_city(id,name,code,parentid) 可形成树状结构。
数据如下:
0,中国,null
1, 北京,0
2,海淀,1
3,朝阳,1
4,东城,1
5,天津,0
6,和平,5
7,河东,5
8,河西,5
9,河北,5
10,红桥,5
11,南开,5
12,重庆,0
......
如何写SQL语句查询,北京,天津,重庆....子数据数量?SELECT COUNT(b.id) amount,f2.id FROM
(
  SELECT id,parentid FROM tb_city
)b
right join 
  (
  SELECT id,parentid FROM tb_city
  )f2
on f2.id=b.parentid  GROUP BY f2.id
SQL sqljoin子数量

解决方案 »

  1.   

    with test as (
    select '0' as id,'中国' as name1,'' as pid from dual
    union all
    select '1' as id,'北京' as name1,'0' as pid from dual
    union all
    select '2' as id,'海淀' as name1,'1' as pid from dual
    union all
    select '3' as id,'朝陽' as name1,'1' as pid from dual
    union all
    select '4' as id,'東城' as name1,'1' as pid from dual
    union all
    select '5' as id,'天津' as name1,'0' as pid from dual
    union all
    select '6' as id,'和平' as name1,'5' as pid from dual
    union all
    select '7' as id,'河東' as name1,'5' as pid from dual
    union all
    select '8' as id,'河西' as name1,'5' as pid from dual
    union all
    select '9' as id,'河北' as name1,'5' as pid from dual
    union all
    select '10' as id,'紅橋' as name1,'5' as pid from dual
    union all
    select '11' as id,'南開' as name1,'5' as pid from dual
    union all
    select '12' as id,'重慶' as name1,'0' as pid from dual
    )
     
    select ltrim(SYS_CONNECT_BY_PATH(name1, '==>'), '==>')
      from test
     start with pid is null
    connect by prior id = pid
      

  2.   

    Oracle中的递归查询,start with ...connect by prior
      

  3.   

    比如查询北京下的所有字节点,下面的语句会把所有的子节点,子节点的子节点的子节点……都查出来的select * from tb_city t1 start with t1.parentid = 1 connect by prior t1.id = t1.parentid
      

  4.   

    子数据量是指:例如:想知道id='0'的(中国)子节点的个数?
     SELECT id,parentid FROM tb_city WHERE parentid='0' 这条语句查出的结果集数量。
      

  5.   

    start with ...connect by prior这个我知道,但是,你写这个更复杂些吧!