sql server 2005 'update from' query

2019-08-29 07:01发布

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.

3条回答
The star\"
2楼-- · 2019-08-29 07:22
update jared_test
set user_count = 1
where userid = 
  (select userID from users where email = 'j@j.co.uk')

try this

查看更多
祖国的老花朵
3楼-- · 2019-08-29 07:28

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'
查看更多
男人必须洒脱
4楼-- · 2019-08-29 07:39

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)

查看更多
登录 后发表回答