0

我在从联接更新表时遇到问题。我做了很多次这种更新,但现在它不起作用。这是原始查询:

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 <> b.strata。我的目标是使这两个彼此相等。所以我认为在我的更新查询之后,我不应该在我的选择查询中得到任何结果。但实际上没有任何改变。更新后我仍然得到相同的 218 结果。

有任何想法吗?

4

3 回答 3

0

如果 218 条记录设置为 ,MAP_Entrance_Population则您所描述的情况可能会发生。在这种情况下,您的选择查询将带回行,因为不等于或其他任何内容,并且您的更新查询将更新为已设置为,但仍不等于。strataNULLNULLNULLsurveydatastrataNULLNULL

当您发现令人惊讶的事情时,您无法完全弄清楚 SQL 中的比较运算符会发生什么,通常根本原因是您将某些东西与NULL.

于 2013-10-01T06:25:13.227 回答
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
 )
于 2013-10-01T06:13:02.953 回答
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
于 2013-10-01T06:23:21.007 回答