【发布时间】:2019-07-17 14:04:14
【问题描述】:
我有 2 个表,如果不匹配,我希望 case 语句子查询设置返回值字符串值“Rural”,如果为真,则设置“Urban”。我需要查询来查找表 2 以查看城市名称是否存在。
目前我的查询总是返回错误值“农村”
, CASE --This CASE is identifying Urban communities as listed in the contract, and leaving the rest as Rural.
WHEN t1.city in (select top 1 city from t1
left join t2 on t2.city2 = t1.city
where t2.city2 = t1.city
)
then 'Urban'
ELSE 'Rural'
end as URBAN_RURAL
select t1.city
, t2.city2
, CASE --This CASE is identifying Urban communities and leaving the rest as Rural.
WHEN Exists (select top 1 from t1 where t1.city = t2.city2)
then 'Urban'
ELSE 'Rural'
end as Urban_Status;
from t1 with (nolock)
left join t2 with (nolock)
on t1.city = t2.city
我想使用查找表,因为我们可能正在修改符合条件的城市,并且只是在该表中添加或删除名称 t2。因此,如果 case 语句可以为两个表中的匹配结果返回 Urban 字符串值,并且为不匹配的结果返回农村字符串值,那将是理想的。
样本结果是
City City2 UrbanRural
Orono NULL Rural
Bangor Bangor Urban
Machias Null Rural
【问题讨论】:
-
您使用的是什么关系型数据库?此外,样本数据和预期结果也很有帮助。
-
T1 是不是只有城市,T2 是农村?仅仅根据一个没有做你想做的事情的查询,很难弄清楚你需要什么。
-
我会记住这些问题,非常感谢您的回复。我弄清楚为什么我的查询不起作用。在 t2 表中,城市名称在所有名称中都有一个额外的空格,因此 SQL 并没有从一开始就加入这两个表。
-
旁白:
exists查询需要但会忽略 选择列表。也就是说,top 1只会让读者感到困惑,但不会影响性能。您也可以选择1、0、NULL、1 / 0或42。