比如a中有10条记录,b的记录数不确定
使用select DISTINCT a.*,b.* from a inner join b当a和b为一对一关系时将返回10条记录,当a和b为一对多的关系时将返回大于或小于10条的记录,我现在想实现的功能是当a和b为一对多的关系的时候a中依然返回10条记录,填充的标准为如果b中没有符合条件的记录填充为null(这点和left join一样),当b中有多条符合条件的记录的时候用第一条符合条件的记录填充,我以前一直使用子查询返回需要的字段,但这样会使SELECT语句变的非常烦琐(估计效率也低^-^),请问大虾们有没有什么比较好的,简单的方法可以达到这个目的?

解决方案 »

  1.   

    1.先根据左联结得到一个大于等于10上的数据集
    select DISTINCT a.*,b.* from a left join b on a.id=b.id2.再根据上面的数据集取出每个不同id的一行
    这样就能保证只有10行了
      

  2.   

    ----创建测试数据
    declare @ta table(id int identity(1,1),name varchar(10))
    declare @tb table(id int identity(1,1),name varchar(10),dt datetime)
    insert @ta(name)
    select 'a1' union all
    select 'a2' union all
    select 'a3' union all
    select 'a4' union all
    select 'a5' union all
    select 'a6' union all
    select 'a7' union all
    select 'a8' union all
    select 'a9' union all
    select 'a10' 
    insert @tb(name,dt)
    select 'a1',getdate() union all
    select 'a1',getdate() union all
    select 'a1',getdate() union all
    select 'a2',getdate() union all
    select 'a2',getdate() union all
    select 'a3',getdate() union all
    select 'a4',getdate() union all
    select 'a5',getdate() union all
    select 'a5',getdate() union all
    select 'a6',getdate() union all
    select 'a7',getdate() union all
    select 'a8',getdate() ----查询
    select * from @tA a left join @tB b on a.name = b.name
    and b.id = (select top 1 id from @tB where name = b.name)