sql server 2005 'update from' query

拈花ヽ惹草 提交于 2019-12-13 04:25:25

问题


I'm trying to update a table based upon the user id from another table. I've come across the Update from syntax but I'm struggling to write my query correctly.

The below code should show you what I'm attempting to do. When i run it i get 0 rows affected.

    update jared_test
       set user_count  = 1
      from new_user nuj
inner join (select us.userID
              from users us
             where us.email = 'j@j.co.uk') u on nuj.userid = u.userid

/********EDIT*******************\

I discovered there was a problem with my Cursor loop that was preventing this from working, so this does actually work. However I'd be interested if a where is better than a from in this instance for optimisations.


回答1:


I'm not 100% on why the other solutions are using a subselect which will perform slower than a regular join most often. Though taos subselect is essentially a regular join just written interestingly.

update aliasName
set aliasName.user_count =1 
from new_user aliasName
inner join users u on aliasName.userid = u.userid
where email = 'j@j.co.uk'



回答2:


update jared_test
set user_count = 1
where userid = 
  (select userID from users where email = 'j@j.co.uk')

try this




回答3:


You don't seem to be establishing any relationship between the table "jared_test" and the two tables that you are selecting by, "new_user/nuj" and "users/us".

Did you mean this?

update nuj
set user_count  = 1
from new_user nuj
inner join (select us.userID
            from users us
            where us.email = 'j@j.co.uk') u on nuj.userid = u.userid

(if so, a standard update as @Devan suggested would make more sense)



来源:https://stackoverflow.com/questions/6029854/sql-server-2005-update-from-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!