Warm tip: This article is reproduced from serverfault.com, please click

Exclude value if they share the same ID

发布于 2020-11-30 13:51:44

I have this statement in my Access database: It lists Magazzino.Codice from 2 tables and the relating quantities.

SELECT Magazzino.Codice, Magazzino.Qnt
FROM Magazzino
WHERE (((Magazzino.[Prossimo_arrivo]) Is Null) And ((Magazzino.Qnt)<30) And ((Magazzino.[Fascia_I])=True));
UNION ALL --Joins allowing duplicates
SELECT Magazzino.Codice, Magazzino.Qnt 
FROM  Magazzino
WHERE (((Magazzino.[Prossimo_arrivo]) Is Null) And ((Magazzino.Qnt)<10) And ((Magazzino.[Fascia_II])=True));

I wish to add a statement avoiding to list Magazzino.Codice if the same ID is present on a third table Magazzino Grezzi. How can I get this?

Questioner
Andrea
Viewed
0
Gordon Linoff 2020-11-30 21:54:52

First, simplify the logic assuming you don't want duplicates form this table:

SELECT m.Codice, m.Qnt
FROM Magazzino as m
WHERE m.[Prossimo_arrivo]) Is Null AND
      ( (m.Qnt < 30 AND m.[Fascia_I] = True) OR
        (m.Qnt < 10 AND m.[Fascia_II] = False) OR
      )

Then use IN or EXISTS:

SELECT m.Codice, m.Qnt
FROM Magazzino as m
WHERE m.[Prossimo_arrivo]) Is Null AND
      ( (m.Qnt < 30 AND m.[Fascia_I] = True) OR
        (m.Qnt < 10 AND m.[Fascia_II] = False) OR
      ) AND
      NOT EXISTS (SELECT 1
                  FROM Magazzino_Grezzi as mg
                  WHERE mg.Codice = m.Codice
                 );

If you really want some rows to be duplicated (those that meet both conditions), then you can add the NOT EXISTS clause to both your subqueries.