我有2个查询在同一个表上以相同的条件执行SELECT。你能帮我删除这个重复吗?
if exists(select count(1)
from (<table>) t
where (<condition>)
having count(1) = 1)
set @yes = 1
if @yes = 1
select @x = X
from (<table>) t
where (<condition>)
答案 0 :(得分:2)
您的代码相当于:
select @yes = 1,@x=max(X) from (<table>) t
where (<condition>)
having count(1) = 1
答案 1 :(得分:1)
EXISTS
可以作为另一个WHERE
条件:
SELECT @x = X
FROM <table> t
WHERE <condition>
AND EXISTS (
SELECT 1
FROM <table> t1
WHERE <condition>
HAVING count(*) = 1
);
基本上,只有当只有行符合时才会从X
中选择<table>
。
或者(可能更快):
SELECT @x = X
FROM <table> t
WHERE <condition>
AND NOT EXISTS (
SELECT 1
FROM <table> t1
WHERE <condition>
AND t1.id <> t.id -- no other row satisfies same conditions
);
id
是主键或<table>
反向逻辑:仅选择符合条件的行,如果没有其他行符合。
答案 2 :(得分:1)
请检查你的意思是:
select
@x = X
from
(<table>) t
where
(<condition>)
group by X
having count(*) = 1
OR
select
@x = X
from(
select
count(*) over() cnt, X
from
(<table>) t
where
(<condition>)
)a
WHERE a.cnt=1
答案 3 :(得分:0)
如果表中的“X”字段不为null,则可以使用此查询:
SET @x = null
SELECT @x = X
FROM (<table>) t
WHERE (<condition>)
IF (@x IS NOT NULL) BEGIN SET @yes = 1 END