如何解决SQL Server中两个条件之间的异或
T-sql中有OR
和AND
个运算符。 AND
表示两个条件为真,OR
表示仅第一个条件为真,第二个条件为真或两个条件都为真。
但是我需要像XOR
这样的东西,就像OR
,但是如果两者都为真,则不应用WHERE
条件。
示例:
select *
from [Table]
where Id in (@FromId) XOR TypeId = @TypeId
我的问题是:我应该如何编写此查询,以便如果找到Id in (@FromId)
,它不会检查TypeId =@TypeId
,如果找不到Id in (@FromId)
,它会检查{{1 }}。
我知道我可以写这个来解决问题:
TypeId =@TypeId
但是我想在一个查询中编写它,以简化,提高性能,减少代码,....
谢谢。
解决方法
我并不为此感到疯狂,但是...
if exists(select * from [Table] where Id in (@FromId)) begin
select * from [Table] where Id in (@FromId)
end
else begin
select * from [Table] where TypeId = @TypeId
end
@FromId是CSV还是其他可迭代的实体?我将其转换为表并进行连接,而不是使用IN运算符并导致性能下降。
,您可以使用窗口函数在单个查询中执行此操作:
select t.*
from (
select t.*,max(case when id in (@FromId) then 1 else 0 end) has_from_id
from mytable t
) t
where id in (@FromId) or (has_from_id = 0 and typeId = @typeId)
另一种典型的方法是union all
和not exists
:
select t.*
from mytable t
where id in (@FromId)
union all
select t.*
from mytable t
where
typeId = @typeId
and not exists (select 1 from mytable where id in (@FromId))
,
基本上,异或可以表示为AND和OR,如下所示:
(cond1 AND NOT cond2) OR (NOT cond1 AND cond2)
因此您的查询可以写为
select *
from [Table]
where (Id in (@FromId) AND TypeId <> @TypeId) OR (Id NOT IN (@FromId) AND TypeId = @TypeId)
,
SQL Server中的XOR是^。请尝试一下
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。