我在从联接更新表时遇到问题。我做了很多次这样的更新,但现在它不起作用。 这是原始查询:
select
surveydatakey
,a.Strata as [surveydata strata]
,SurveyPeriod
,DateOfSurvey
,StationLocation
,a.CardType
,a.timeperiod
,station_entrance
,Direction
,DayType
,EntranceType
,b.Strata as ActuaStrata
,StartDate
,currentdate
from surveydata a
inner join MAP_Entrance_Population b
on a.station_entrance_id = b.station_entrance_id
and a.timeperiod = b.tp
and a.strata <> b.strata
where mode = 'train'
and a.strata not in (1,14,15,21,22,23)
and dateofsurvey between startdate and currentdate
order by a.strata
现在这是更新查询:
begin tran
update a
set a.strata = b.strata
from surveydata a
inner join MAP_Entrance_Population b
on a.station_entrance_id = b.station_entrance_id
and a.timeperiod = b.tp
and a.strata <> b.strata
where mode = 'train'
and a.strata not in (1,14,15,21,22,23)
and dateofsurvey between startdate and currentdate
搜索查询生成218个结果,更新说它会更改218个结果。 在我的搜索查询中,我的条件是a.strata&lt;&gt; b.strata。我的目标是让这两个人相等。所以我想在我的更新查询后,我不应该在我的选择查询中得到任何结果。但实际上并没有改变。在进行更新后,我仍然得到相同的218个结果。
有什么想法吗?
答案 0 :(得分:0)
是否可以,因为表B中没有任何记录根据您的连接条件加入表A?
尝试运行以下查询
select *
from surveydata a
where mode = 'train'
and a.strata not in (1,14,15,21,22,23)
and dateofsurvey between startdate and currentdate
and not exists
(
SELECT 1
from MAP_Entrance_Population b
WHERE a.station_entrance_id = b.station_entrance_id
and a.timeperiod = b.tp
and a.strata <> b.strata
)
答案 1 :(得分:0)
尝试以下两个查询
select
.
.
.
from surveydata a
inner join MAP_Entrance_Population b
on a.station_entrance_id = b.station_entrance_id
and a.timeperiod = b.tp
where a.strata <> b.strata
and mode = 'train'
and a.strata not in (1,14,15,21,22,23)
and dateofsurvey between startdate and currentdate
order by a.strata
更新
update a
set a.strata = b.strata
from surveydata a
inner join MAP_Entrance_Population b
on a.station_entrance_id = b.station_entrance_id
and a.timeperiod = b.tp
where a.strata <> b.strata
and mode = 'train'
and a.strata not in (1,14,15,21,22,23)
and dateofsurvey between startdate and currentdate
答案 2 :(得分:0)
如果MAP_Entrance_Population
中的218条记录strata
设置为NULL
,则您所描述的内容可能会发生。在这种情况下,您的选择查询会将行恢复为NULL
is not equal to NULL
或其他任何内容,并且您的更新查询将更新surveydata
以将strata
设置为NULL
,这是仍然不等于NULL
。
当您发现令人惊讶的事情时,您无法理解SQL中的比较运算符,通常根本原因是您将某些内容与NULL
进行比较。