1

我有 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>)
4

4 回答 4

2

您的代码相当于:

select @yes = 1,@x=max(X) from (<table>) t   
       where  (<condition>)   
       having count(1) = 1
于 2012-12-26T10:41:13.027 回答
1

EXISTS可以作为另一个WHERE条件:

SELECT @x = X
FROM   <table> t
WHERE  <condition>
AND    EXISTS (
    SELECT 1
    FROM   <table> t1
    WHERE  <condition>
    HAVING count(*) = 1
    );

基本上它仅在X只有row qualifying时才会选择。 或者(可能更快):<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>.
反向逻辑:仅选择符合条件的行,如果没有其他行符合条件

于 2012-12-26T10:29:20.417 回答
1

请检查你是否是这个意思:

    select 
      @x = X   
    from 
      (<table>) t   
    where  
      (<condition>)
    group by X
    having count(*) = 1

或者

select 
    @x = X  
from(
    select 
        count(*) over() cnt, X    
    from 
        (<table>) t  
    where  
        (<condition>)
)a
WHERE a.cnt=1
于 2012-12-26T10:29:32.007 回答
0

如果表中的“X”字段不为空,则可以使用此查询:

SET @x = null

SELECT @x = X   
        FROM (<table>) t   
        WHERE (<condition>)
IF (@x IS NOT NULL) BEGIN SET @yes = 1 END
于 2012-12-26T10:33:04.103 回答