有表A,B
A结构
  id, num
   1    
   2B结构 
   id, name
    1    n1
    2,   n2A表与B表 id关联
如何用一个sql语句 将B表中name值 插入到A表相对应的num中

解决方案 »

  1.   

    update a set num=b.name from a join b on a.id=b.id
      

  2.   

    update t set num=r.name from a t inner join r on t.id=r.id
    --注意,NUM列必须为字符型
      

  3.   


    /*
    为了学习sql,强制自己用sql操作表,即使再简单的查询也要用sql测试
    */
    if object_id('t1') is not null 
    drop table t1
    go
    if object_id('t2') is not null
    drop table t2
    go 
    create table t1
    (
    [id] int,
    num varchar(10)
    )
    go
    create table t2
    (
    [id] int,
    [name] varchar(10)
    )go
    insert t1
    select 1,null
    union all
    select 2,null
    go
    insert t2
    select 1,'n1'
    union all
    select 2,'n2'
    go
    update a set a.num=b.[name] from t1 as a join t2 as b on a.[id]=b.[id]
    /*
    (所影响的行数为 2 行)
    */