Mysql查询除外

时间:2012-12-11 16:54:15

标签: mysql sql

我需要进行类似的查询:

SELECT DISTINCT Carta_ID
FROM Carta_Alarme
INNER JOIN Alarme ON Carta_Alarme.Alarme_ID = Alarme.ID
WHERE (
YEAR( Alarme.dtOcorrencia ) = 2011
) NOT
IN (

SELECT DISTINCT Carta_ID
FROM Carta_Alarme
INNER JOIN Alarme ON Carta_Alarme.Alarme_ID = Alarme.ID
WHERE (
YEAR( Alarme.dtOcorrencia ) = 2012
)
)

首先选择的结果是(1,5,6)。 “NOT IN”之后的另一个选择的结果是(1,2,3,4,5),但总查询的结果是(1,2,3,4,5),我只需要(6)。

所以我需要的是这个选择之间的区别,我得到的是INTERSECT

3 个答案:

答案 0 :(得分:2)

SELECT DISTINCT Carta_ID
FROM Carta_Alarme
INNER JOIN Alarme ON Carta_Alarme.Alarme_ID = Alarme.ID
WHERE (
YEAR( Alarme.dtOcorrencia ) = 2011
) AND Carta_ID NOT
IN (

SELECT DISTINCT Carta_ID
FROM Carta_Alarme
INNER JOIN Alarme ON Carta_Alarme.Alarme_ID = Alarme.ID
WHERE (
YEAR( Alarme.dtOcorrencia ) = 2012
)
)

答案 1 :(得分:1)

SELECT Carta_ID
FROM Carta_Alarme
INNER JOIN Alarme ON Carta_Alarme.Alarme_ID = Alarme.ID
GROUP BY Carta_ID
HAVING sum(YEAR(Alarme.dtOcorrencia) = 2011) > 0 
   and sum(YEAR(Alarme.dtOcorrencia) = 2012) = 0 

答案 2 :(得分:0)

SQL Fiddle

这实际上是minus set operation

SELECT DISTINCT ca.Carta_ID
FROM Carta_Alarme ca
INNER JOIN Alarme a ON ca.Alarme_ID = a.ID
left join (SELECT DISTINCT Carta_ID
           FROM Carta_Alarme
           INNER JOIN Alarme ON Carta_Alarme.Alarme_ID = Alarme.ID
           WHERE YEAR( Alarme.dtOcorrencia ) = 2012) ca2 on ca2.Carta_id = ca.Carta_id
WHERE YEAR( a.dtOcorrencia ) = 2011
      and ca2.Carta_id is null