[英]How to get the proper SQL result from a query
我的数据库中有一个视图,它使用了几个表,并且一切都像现在这样正常工作。 我想根据是否在另一个表中找到特定匹配来添加另一个列/值。 我在其他人中使用过类似的迭代,但这次我得到了 NULL 结果,即使有匹配。
基本上:
表_2
ID | 价值 | 文本 |
---|---|---|
1 | 错过 | 一些文字 |
1 | 错过 | 其他文字 |
2 | 打 | 好的 |
2 | 错过 | 总是 |
3 | 打 | 还有什么 |
与另一个包含一个值的表相关,该值等于 Table_2 中的 ID。
我想使用 case when 并基于此设置文本;
select
somefield1,
somefield2,
somefield3,
case
when 2.ID is not null then 'Real'
else 'Fake'
end somefield4
from
table_1 1 (nolock)
left join
(select top (1) ID from table_2 where Value = 'Hit') 2 on 1.ID = 2.ID
如果我运行这个脚本:
select top (1) ID
from table_2
where Value = 'Hit' and ID = 2
它返回:2
如果我运行这个:
select top (1) ID
from table_2
where Value = 'Hit' and ID = 1
它返回:NULL
但是当我运行视图时,我每次都会得到“假”,即使存在匹配并且查询返回一个值。
如果我理解正确,您可以使用exists
来检查另一个表中是否存在相应的行。 这看起来像:
select t2.*,
(case when exists (select 1
from table_1 t1
where t1.id = t2.id and t1.event = 'Hit'
)
then 'real' else 'fake'
end)
from table_2 t2;
为了提高性能,您需要在table_1(id, event)
上建立索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.