使用 IN 运算符将值与 2 个不同的列进行比较
compare value with 2 different columns using the IN operator
我遇到一种情况,我需要将一列的值与我的设置中的两列进行比较 table。
目前我有这个有效的查询
declare @t int = 3
select 1
where @t = (select s.RelationGDGMID from dbo.tblSettings s )
or
@t = (select s.RelationGTTID from dbo.tblSettings s )
但我想知道我是否可以在不读取 tblSettings 2 次的情况下做到这一点,然后我尝试了这个
declare @t int = 3
select 1
where @t in (select s.RelationGDGMID, s.RelationGTTID from dbo.tblSettings s )
这不能编译,它 returns
Only one expression can be specified in the select list when the
subquery is not introduced with EXISTS
那么我如何在不读取 tblSettings 2 次的情况下执行此操作,一个解决方案是使用 EXISTS,就像错误提示我一样
declare @t int = 3
select 1
where exists (select 1 from dbo.tblSettings s where s.RelationGDGMID = @t or s.RelationGTTID = @t)
是的,它有效,只读取 tblSettings 一次,所以我可以使用它。
但我仍然想知道是否有办法让它与 IN
operator
一起工作
毕竟,当我这样做时
declare @t int = 3
select 1
where @t in (3, 1)
可以正常工作,
那么为什么
where @t in (select s.RelationGDGMID, s.RelationGTTID from dbo.tblSettings s )
不起作用,实际上它也是 returns (3, 1)
?
如果列的类型相同,一种方法是使用 UNION。
where @t in (select s1.RelationGDGMID from dbo.tblSettings s1 UNION
select s2.RelationGTTID from dbo.tblSettings s2)
之所以可行,是因为它返回一个值集(1 列有值)。 where @t in (3, 1)
起作用的原因是因为这相同,它返回一个值集(值 3 和值 1)。
也就是说我更喜欢 EXISTS
而不是 IN
因为这可以产生更好的查询计划。
我遇到一种情况,我需要将一列的值与我的设置中的两列进行比较 table。
目前我有这个有效的查询
declare @t int = 3
select 1
where @t = (select s.RelationGDGMID from dbo.tblSettings s )
or
@t = (select s.RelationGTTID from dbo.tblSettings s )
但我想知道我是否可以在不读取 tblSettings 2 次的情况下做到这一点,然后我尝试了这个
declare @t int = 3
select 1
where @t in (select s.RelationGDGMID, s.RelationGTTID from dbo.tblSettings s )
这不能编译,它 returns
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS
那么我如何在不读取 tblSettings 2 次的情况下执行此操作,一个解决方案是使用 EXISTS,就像错误提示我一样
declare @t int = 3
select 1
where exists (select 1 from dbo.tblSettings s where s.RelationGDGMID = @t or s.RelationGTTID = @t)
是的,它有效,只读取 tblSettings 一次,所以我可以使用它。
但我仍然想知道是否有办法让它与 IN
operator
一起工作
毕竟,当我这样做时
declare @t int = 3
select 1
where @t in (3, 1)
可以正常工作,
那么为什么
where @t in (select s.RelationGDGMID, s.RelationGTTID from dbo.tblSettings s )
不起作用,实际上它也是 returns (3, 1)
?
如果列的类型相同,一种方法是使用 UNION。
where @t in (select s1.RelationGDGMID from dbo.tblSettings s1 UNION
select s2.RelationGTTID from dbo.tblSettings s2)
之所以可行,是因为它返回一个值集(1 列有值)。 where @t in (3, 1)
起作用的原因是因为这相同,它返回一个值集(值 3 和值 1)。
也就是说我更喜欢 EXISTS
而不是 IN
因为这可以产生更好的查询计划。