将NOT IN转换为NOT EXISTS SQL firebird

时间:2016-11-28 11:04:28

标签: sql firebird

我想将此信息转换为不存在。

SELECT * FROM MYCARD T1
WHERE T1.IDMONEY = 5 AND T1.IDCARD = 80
AND EXISTS (
    SELECT IDCARD, YEAR, MONEY 
    FROM MYCARD T2
    WHERE T2.IDCARD = T1.IDCARD 
    AND T2.YEAR = T1.YEAR
    AND T2.MONEY = T1.MONEY
    GROUP BY T2.IDCARD, T2.YEAR, T2.MONEY 
    HAVING COUNT(T2.IDCARD) > 1
)
AND T1.ID not in (   -- THIS NOT IN TO NOT EXISTS
    select min(ID)
    from MYCARD
    WHERE IDMONEY = 5
    AND IDCARD = 80
    group by IDCARD, YEAR
)

我想获得ID与min(ID)不同的值。这不是很好,但我需要更优化的查询。我尝试使用类似的东西,但似乎是正确的,但它没有优化:

AND EXISTS (
    select min(ID)
    from MYCARD
    WHERE IDMONEY = 5
    AND IDCARD = 80
    group by IDCARD, YEAR
    HAVING T1.ID = MIN(ID)
)

3 个答案:

答案 0 :(得分:0)

如果两次使用not exists,则可以执行以下操作:

select * 
from MYCARD T1
where not exists 
(
 select 1 
 from MYCARD T2
 where ID = T1.ID and IDMONEY = 5 AND IDCARD = 80 and not exists 
 (
   select 1 
   from MYCARD 
   where IDMONEY = 5 AND IDCARD = 80 and ID < T2.ID)
)

答案 1 :(得分:0)

不完全是NOT EXISTS,而是EXISTS

        -- The original query  selects the values that
        -- don't have the *minimum* value per {idcard,idmony}.
        -- NOT the minimum := a lower value exists
        -- --------------------------------------------------
SELECT * 
FROM mycard t1
WHERE EXISTS ( SELECT *
    FROM mycard x
    WHERE x.idmoney = t1.idmoney
    AND x.idcard = t1.idcard
    AND x.id < t1.id -- a lower value exists
    )
AND t1.idmoney = 5
AND t1.idcard = 80
        ;

答案 2 :(得分:-2)

select * from MYCARD T1 WHERE NOT EXISTS (
select 1 from MYCARD WHERE IDMONEY = 5
AND IDCARD = 80
group by IDCARD, YEAR)