SQL 服务器中两个条件之间的异或
Xor between two conditions in 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)
,它会检查 TypeId =@TypeId
.
我知道我可以写这个来解决问题:
select * from [Table] where Id in (@FromId)
if @@ROWCOUNT =0
select * from [Table] where 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 还是其他可迭代实体?我会将其转换为 table 并加入,而不是使用 IN 运算符并遭受性能损失。
您可以使用 window 函数在单个查询中执行此操作:
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))
基本上 XOR 可以用 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 服务器中的 XOR 是 ^。请试一试
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)
,它会检查 TypeId =@TypeId
.
我知道我可以写这个来解决问题:
select * from [Table] where Id in (@FromId)
if @@ROWCOUNT =0
select * from [Table] where 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 还是其他可迭代实体?我会将其转换为 table 并加入,而不是使用 IN 运算符并遭受性能损失。
您可以使用 window 函数在单个查询中执行此操作:
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))
基本上 XOR 可以用 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 服务器中的 XOR 是 ^。请试一试