2

下面你可以看到我的简化数据库模型:

在此处输入图像描述

由于错误,Job.location列中只有空值,其中条目属于某个P ​​lan。因此,我想更新与此计划关联的所有作业,将Job.location设置为拥有此计划的User的Location.name 。

我试过这个 SQL 查询:

    update dbo.Job set location =

        (select name from dbo.Location as loc where

           loc.objectid = objectid  and loc.user_id in 

           (select userid from dbo.[Plan] as p where p.planid = 20))

        where planid = 20

但是,结果总是:0 rows affected。子查询本身可以正常工作。

我怎样才能实现具有特定计划的所有工作都受到影响?

4

2 回答 2

6

我认为您的错误可能是您objectid在 subquery 中没有列的别名loc.objectid = objectid,因此当您自己运行子查询时,它就像loc.objectid = loc.objectid在更新中运行它时一样loc.objectid = dbo.Job.objectid

在您的架构中,用户可以有多个位置,但假设每个用户和对象只有一个位置,您可以尝试以下查询:

update dbo.Job set
    location = L.Name
from dbo.Job as J
    inner join dbo.[Plan] as P on P.planid = J.planid
    inner join dbo.Location as L on L.user_id = P.userid and L.objectid = J.objectid
于 2012-12-12T08:36:55.040 回答
1
UPDATE
j
SET Job.location = loc.name
FROM
Job j
INNER JOIN Plan p ON j.planid = p.planid
INNER JOIN aspnet_Users u ON p.userid = u.UserId
INNER JOIN Location loc ON u.UserId = loc.user_id
WHERE j.planid = 20 
AND p.planid = 20
于 2012-12-12T08:40:35.113 回答