UPDATE SET不能与NOT IN(SELECT)一起使用?

时间:2014-09-07 09:10:32

标签: mysql sql

我的SQL UPDATE查询有问题:

UPDATE gon_nu.migration_threads 
    SET AuthorID = 461376 
WHERE AuthorID NOT IN (SELECT id AS AuthorID 
                       FROM prod_playing.users_userprofile 
                       WHERE username != 'OldPlayingUser');

它会响应匹配但受影响的是0行。如何在prod_playing.users_userprofile中不存在AuthorID时将AuthorID更新为461376?

2 个答案:

答案 0 :(得分:0)

如果users_userprofile.id NULL username = 'OldPlayingUser' UPDATE gon_nu.migration_threads SET AuthorID = 461376 WHERE AuthorID NOT IN (SELECT id AS AuthorID FROM prod_playing.users_userprofile WHERE username <> 'OldPlayingUser' and id is not null ); where not in,则查询无效的一种可能性。这表明此查询可能会执行您想要的操作:

where

但是,您的问题表明您在UPDATE gon_nu.migration_threads SET AuthorID = 461376 WHERE AuthorID NOT IN (SELECT id AS AuthorID FROM prod_playing.users_userprofile WHERE username = 'OldPlayingUser' and id is not null ); 子句中可能有太多否定。将{{1}}与子查询一起使用是不常见的,其中{{1}}条件不等于。也许这就是你想要的:

{{1}}

答案 1 :(得分:0)

我更喜欢不存在,因为它更清晰:

UPDATE MT
SET
AuthorID = 461376 
FROM gon_nu.migration_threads AS MT
WHERE
    NOT EXISTS(
            SELECT ID 
            FROM prod_playing.users_userprofile AS UP
            WHERE 
                UP.id = MT.AuthorID
            AND     (UP.username != 'OldPlayingUser'
            OR  UP.username IS NULL)
           )

此外,您可以轻松地将更新切换为选择,以查看您要更新的记录!