Search code examples
sqlms-accesssubquerynot-exists

Ms Access - show difference between two query results


I have written two queries that show different results for the same 3 fields:

All relevant data, showing ITEM_NUMBER, MFR, and MFR_PN, returning 164 different lines

SELECT NewMNFData.ITEM_NUMBER, NewMNFData.MFR, NewMNFData.MFR_PN
FROM NewMNFData INNER JOIN ([B-K Data] INNER JOIN [BK-Analogic-PN-CDB2006-import] ON [B-K Data].[B-K no] = [BK-Analogic-PN-CDB2006-import].[BK PN]) ON NewMNFData.ITEM_NUMBER = [BK-Analogic-PN-CDB2006-import].[Analogic PN];

And another query which shows unique instances of ITEM_NUMBER, MFR, and MFR_PN which returns 101 different lines.

SELECT NewMNFData.ITEM_NUMBER, Min(NewMNFData.MFR) AS MinOfMFR, Min(NewMNFData.MFR_PN) AS MinOfMFR_PN
FROM NewMNFData INNER JOIN ([B-K Data] INNER JOIN [BK-Analogic-PN-CDB2006-import] ON [B-K Data].[B-K no] = [BK-Analogic-PN-CDB2006-import].[BK PN]) ON NewMNFData.ITEM_NUMBER = [BK-Analogic-PN-CDB2006-import].[Analogic PN]
GROUP BY NewMNFData.ITEM_NUMBER;

The difference is the uniqueness on ITEM_NUMBER (there are the same ITEM_NUMBER up to two times, with different MFR and MFR_PN)

I want to create a third query that shows all record from query 1 that is not present in query 2, showing 63 lines.

I thought of using the following query using WHERE NOT EXISTS, but it returns an empty set.

SELECT AllMFR.*
FROM AllMFR
WHERE NOT EXISTS(
SELECT UniqueMFR.*
FROM UniqueMFR);

Solution

  • This would be much easier if Access implemented all of the ISO SQL set operators (UNION, INTERSECTION, REMOVE) because what you want is the REMOVE operation (called MINUS in Oracle). However, like MySql MS-Access only implements the UNION operator. Fortunately, MySql has a doc page that explains how to implement the MINUS (REMOVE) operator functionality in SQL without the keyword

    As it happens, you got pretty close, you just need to add an extra set of conditions to your NOT EXISTS query.

    So something like this should work:

    SELECT AllMFR.*
    FROM AllMFR
    WHERE NOT EXISTS(
        SELECT *
        FROM UniqueMFR
        WHERE UniqueMFR.ITEM_NUMBER = AllMFR.ITEM_NUMBER
          AND UniqueMFR.MFR         = AllMFR.MFR
          AND UniqueMFR.MFR_PN      = AllMFR.MFR_PN
        );