Search code examples
pythonsqlpython-2.7ms-accesspypyodbc

Python filter one list based on values that do not exist in another list


Trying to filter results of a query on a Table A by 2 values not found in a Table B. What would be the proper syntax and approach?

 import pyodbc
 MDB = 'C:/db/db1.mdb'; DRV = '{Microsoft Access Driver (*.mdb)}'; PWD = 'pw'
 con = pyodbc.connect('DRIVER={};DBQ={};PWD={}'.format(DRV,MDB,PWD))
 cur = con.cursor()
 SQLA = 'SELECT * FROM TABLE1;' # your query goes here
 SQLB = 'SELECT * FROM TABLE2;' # your query goes here
 rows1 = cura.execute(SQLA).fetchall()
 rows2 = cura.execute(SQLB).fetchall()
 cur.close()
 con.close()
 for rit in rows1: 
     for git in rows2: 
        if (rit[1] and rit[2]) not in (git[1] and git[2]):
           print ((rit[1])  (rit[2]))

Solution

  • Simply use a pure SQL solution with the familiar LEFT JOIN... IS NULL / NOT EXISTS / NOT IN. Below are equivalent queries, compliant in MS Access, returning rows in TableA not in TableB based on col1 and col2.

    LEFT JOIN...IS NULL

    SELECT a.*
    FROM TABLEA a
    LEFT JOIN TABLEB b
    ON a.col1 = b.col1 AND a.col2 = b.col2
    WHERE b.col1 IS NULL AND b.col2 IS NULL
    

    NOT EXISTS

    SELECT a.*
    FROM TABLEA a 
    WHERE NOT EXISTS 
      (SELECT 1 FROM TABLEB b
       WHERE a.col1 = b.col1 AND a.col2 = b.col2)
    

    NOT IN

    SELECT a.*
    FROM TABLEA a
    WHERE a.col1 NOT IN (SELECT col1 FROM TABLEB)
    AND a.col2 NOT IN (SELECT col1 FROM TABLEB)