简体   繁体   English

SQL Server 2005“更新自”查询

[英]sql server 2005 'update from' query

I'm trying to update a table based upon the user id from another table. 我正在尝试根据另一个表中的用户ID更新表。 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. 当我运行它时,我得到0行影响。

    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. 我发现Cursor循环存在问题,阻止了此工作,因此这确实有效。 However I'd be interested if a where is better than a from in this instance for optimisations. 但是,我想知道在这种情况下,哪里比哪里更好。

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

try this 尝试这个

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". 您似乎并未在表“ jared_test”和您通过其选择的两个表“ new_user / nuj”和“ 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) (如果是这样,则@Devan建议的标准更新会更有意义)

I'm not 100% on why the other solutions are using a subselect which will perform slower than a regular join most often. 我不是100%为何其他解决方案使用的子选择会比常规联接执行得最慢。 Though taos subselect is essentially a regular join just written interestingly. 尽管taos subselect本质上是一个有趣的常规联接。

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM