update c set bid = b.id from c inner join a on c.aid = a.id inner join b on a.flag = b.flag

解决方案 »

  1.   

    谢谢salonstar(Tommy),还有为NULL的如何处理呢?
      

  2.   

    update c
    set bid=b.bid
    from c
    join a on a.id=c.aid
    join b on a.flag=b.flag
      

  3.   

    update c
    set bid=t.id
    from c
    join a on a.id=c.aid
    join (
           select min(id) as 'id'
                  ,flag
           from b 
           group by flag
          ) t on a.flag=t.flag
      

  4.   

    declare @a table(id int,flag varchar(10))
    declare @b table(id int,flag varchar(10))
    declare @c table(aid int,bid int)
    insert @a
    select 1,'one' union
    select 2,'two' union
    select 3,'three' union
    select 4,'four' union
    select 5,'five' union
    select 6,'six'
    insert @b
    select 1,'three' union
    select 2,'four' union
    select 3,'two' union
    select 4,'one' union
    select 5,'one' union
    select 6,'five' union
    select 7,'six'
    insert @c
    select 1,4 union
    select 2,3 union
    select 3,null union
    select 4,5 union
    select 5,2 union
    select 6,7--更新
    update c
    set bid=b.id
    from @c c
    join @a a on a.id=c.aid
    join (
           select min(id) as 'id'
                  ,flag
           from @b 
           group by flag
          ) b on a.flag=b.flag--查看
    select * from @c--结果
    /*
    aid         bid         
    ----------- ----------- 
    1           4
    2           3
    3           1
    4           2
    5           6
    6           7(所影响的行数为 6 行)
    */
      

  5.   

    declare @b table(id int,flag varchar(10))insert into @b select 1,'one'
    union select 2,'two'
    union select 3,'three'
    union select 4,'four'
    union select 5,'five'
    union select 6,'six'declare @a table(id int,flag varchar(10))insert into @a select 1,'three'
    union select 2,'four'
    union select 3,'two'
    union select 4,'one'
    union select 5,'one'
    union select 6,'one'
    union select 7,'six'declare @c table(aid int,bid int)insert into @c select 1,3
    union select 2,4
    union select 3,null
    union select 4,5
    union select 5,2
    union select 6,7
    update  c  set bid=isnull(c.bid,1) from @c c,(select a.id aid, b.id bid from @a a ,@b b where a.flag = b.flag ) e where c.aid=e.aidselect  * from @c