问题描述:
有两个表tb1,tb2,
tb1的数据结构:uid   uname
======================
1     andy
2     sunny
3     bill
tb2的数据结构
uid   totalcount
======================
1     100tb1,tb2通过uid关联现在我想要的结果是
uid  totalcount
======================
1     100
2     0
3     0就是当tb2中没有数据的时候,查询的结构用0来代替。

解决方案 »

  1.   

    select t1.uid,isnull(t2.totalcount,0) from  t1 left join t2 on t1.uid=t2.uid
      

  2.   


    SELECT a.uid,ISNULL(b.TotalCount,0)
    FROM t1 a LEFT JOIN t2 b
    ON a.uid=b.uid
      

  3.   

    declare @t1 table(uid int ,  uname varchar(10)) 
    insert @t1 select 1,    'andy' 
    insert @t1 select 2,    'sunny' 
    insert @t1 select 3,    'bill' 
    declare @t2 table(uid int,  totalcount int) 
    insert @t2 select 1,    100
    select t1.uid,isnull(t2.totalcount,0) from @t1 t1  left join @t2 t2 on t1.uid=t2.uid 
    /*
    uid                     
    ----------- ----------- 
    1           100
    2           0
    3           0
    */
      

  4.   

    declare @tb1 table(uid int,uname varchar(50))
    insert into @tb1
    select 1,'andy' union all
    select 2,'sunny' union all
    select 3,'bill' declare @tb2 table(uid int,totalcount int)
    insert into @tb2
    select 1,100--select * from @tb1
    --select * from @tb2select a.*,isnull(b.totalcount,0) as totalcount from @tb1 a left join @tb2 b on  a.uid=b.uid
    uid         uname                                              totalcount  
    ----------- -------------------------------------------------- ----------- 
    1           andy                                               100
    2           sunny                                              0
    3           bill                                               0(所影响的行数为 3 行)