微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

SQL Server中两个条件之间的异或

如何解决SQL Server中两个条件之间的异或

T-sql中有ORAND个运算符。 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 allnot 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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?