表A 
uid       name     age 
1         aaa       20 
2         bbb       21 
3         ccc       18表   B 
id   uid                  title     times 
1     1               ggg       2005-11 
2     1               hhh       2005-11 
3     2               jjj       2005-11 
4     1               kkk       2005-11
希望通过一条sql语句查询出列出表A数据加上表A中uid在表B的记录数。
表A中还有个uid=3,那么它的记录数是0,这该怎么显示呢?最后显示结果希望:uid       size(记录数)name     age 
1           3                    aaa        20 
2           1                     bbb       21 
3           0                     ccc       18

解决方案 »

  1.   

    抛砖啦先……
    with a as (
    select 1  uid1 , 'aaa' name,20 age from dual union all
    select 2,'bbb',21 from  dual union all
    select 3,'ccc',18 from  dual 
    ),
    b as (
    select 1 id,1 uid1,'ggg' title,'2005-11' times  from dual  union all
    select 2 ,1,'hhh','2005-11' from dual  union all
    select 3,2,'jjj','2005-11'from dual  union all
    select 4,1,'kkk','2005-11' from dual  
    )
    select a.uid1,count( b.uid1),a.name,a.age  from a,b
    where a.uid1=b.uid1(+)
    group by a.uid1,a.name,a.age
    order by a.uid1--
    1 3 aaa 20
    2 1 bbb 21
    3 0 ccc 18
      

  2.   

    select t.id, count(ts.idb) as "size",t.name, t.age
      from a t
      left join b ts
        on (t.id = ts.id)
     group by t.id, t.name, t.age order by t.id;
      

  3.   


    SELECT A.uid,
           COUNT(1) size,
           A.name,
           A.age
    FROM A,B
    WHERE A.UID=B.UID(+)
    group by A.uid,A.name,A.age
    正确答案~
      

  4.   


    select uid,
           (select count(1) from b where a.uid=b.uid) size,
           name,
           age
      from a
      

  5.   


    另:uid和size都不能用,得用别的名字!
    上机试了才知道还有这种限制呢?不知道为什么!
    话说2楼和3楼的连接方向反了
      

  6.   

    Oracle中有不少关键字如file、level、size、category、class、tpye等等,使用它们做字段名的表在执行INSERT、UPDATE等语句时会引起错误。我们知道在SQL Server中可以给所有表名、字段名都加上[]以彻底防止出现这种情况,而在Oracle中则使用""代替[]。嗯,且慢,只加""不够,""内的字段名还必须大写另外上面的不是连接方向反了,而是b中没有a的uid的时候是错的,将空的数据也计入了
      

  7.   

    select a.uid , nvl((select count(1) from b where b.uid = a.id),0) size , a.name , a.age from a