一个初级问题:update 可否 嵌套select查询?
想将一个特定的结果通过select语句查出,然后更新到当前表的指定记录的某一字段。例如如下语句想要实现将表2的具有“010”编号且列a属性大于等于1的人数填写到表1的编号为010的记录的“人数”字段。
请问这种更新语句是否合法,
另外在ACCESS中使用时发现能够更新,只不过人数算不对——单独执行括号中的语句“SELECT Count(*) FROM 表2 WHERE (((表2.列a)>=1) AND ((表2.编号)="010"))”时得数是"3",但是一旦嵌套到update语句中,set后的结果就成了"1"。
请高手帮忙分析分析,谢谢!UPDATE 表1 SET 表1.人数 = (SELECT Count(*) FROM 表2 WHERE (((表2.列a)>=1) AND ((表2.编号)="010")))
where 表1.编号="010"

解决方案 »

  1.   

    update a set 人数=(select count(*) from t2 where field_a>=1 and 编号='010')
     from t1 a
    where 编号='010'--或
    update a set 人数=b.cnt
     from t1 a
    inner join(select count(*) cnt from t2 where 编号='010' and field_a>=1) b
     on 1=1
    where a.编号='010'--或
    update a set 人数=b.cnt
     from t1 a
    inner join(select count(*) cnt,编号 from t2 where field_a>=1) b
     on a.编号=b.编号
    where a.编号='010'
      

  2.   

    谢谢fcuandy的回答,
    不过,解决方法一中的 a 是 t1表的别名吗? Access中好像不支持 “update 别名 set 列=值 from 表名 别名”的表达法,我用了AS关键字,仍然也不支持。 不知我理解的对不对, 别名是不是必须的?
      

  3.   

    access好多年没用了,记不清了,不好意思.
      

  4.   

    做成个子查询就可以了.
    如:update ta
    set col = t.col
    from ta,(select id,max(col) col from tb group by id) t
    where ta.id = tb.id
      

  5.   

    --上面错了点.
    做成个子查询就可以了. 
    如: update   ta 
    set   col   =   t.col 
    from   ta,(select   id,max(col)   col   from   tb   group   by   id)   t 
    where   ta.id   =   t.id
      

  6.   

    挺受启发的,谢谢大家,
    就是Access好像不支持“update   别名   set   列=值   from   表名   别名”的表达法
    仅仅支持如
    “UPDATE 报名数据 AS ta SET ta.姓名 = "小芳" WHERE (((ta.身份证号)="1"));”
    样的别名表达,似乎不能借助其他表来更新当前表了
      

  7.   


    --楼主这样试试
    update t1
    set 人数=(select count(1) from table2 where 编号=t1.编号 and 列a>=1 )
    from table1 t1
    where
    t1.编号= '010'