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?
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.
"SELECT 1"? why "1"?
@Andrea . . .
EXISTS
checks for the existing of rows. In general, rows need to have a column. I find that1
is the simplest value to type and accurate conveys the purpose of the code.