Python 根据另一个列表中不存在的值过滤一个列表
Python filter one list based on values that do not exist in another list
尝试通过 Table B 中未找到的 2 个值过滤 Table A 上的查询结果。正确的语法和方法是什么?
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]))
只需使用熟悉的 LEFT JOIN... IS NULL / NOT EXISTS / NOT IN
的纯 SQL 解决方案。下面是等效的查询,符合 MS Access,返回表 A 中的行而不是基于 col1 和 col2 的表 B 中的行。
左连接...为空
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
不存在
SELECT a.*
FROM TABLEA a
WHERE NOT EXISTS
(SELECT 1 FROM TABLEB b
WHERE a.col1 = b.col1 AND a.col2 = b.col2)
不在
SELECT a.*
FROM TABLEA a
WHERE a.col1 NOT IN (SELECT col1 FROM TABLEB)
AND a.col2 NOT IN (SELECT col1 FROM TABLEB)
Parfait 提供的 SQL 语句是首选解决方案,但如果您真的想使用双循环方法,则需要更像这样:
for rit in rows1:
match_found = False
for git in rows2:
if (rit[1] == git[1]) and (rit[2] == git[2]):
match_found = True
break
if not match_found:
print(rit)
尝试通过 Table B 中未找到的 2 个值过滤 Table A 上的查询结果。正确的语法和方法是什么?
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]))
只需使用熟悉的 LEFT JOIN... IS NULL / NOT EXISTS / NOT IN
的纯 SQL 解决方案。下面是等效的查询,符合 MS Access,返回表 A 中的行而不是基于 col1 和 col2 的表 B 中的行。
左连接...为空
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
不存在
SELECT a.*
FROM TABLEA a
WHERE NOT EXISTS
(SELECT 1 FROM TABLEB b
WHERE a.col1 = b.col1 AND a.col2 = b.col2)
不在
SELECT a.*
FROM TABLEA a
WHERE a.col1 NOT IN (SELECT col1 FROM TABLEB)
AND a.col2 NOT IN (SELECT col1 FROM TABLEB)
Parfait 提供的 SQL 语句是首选解决方案,但如果您真的想使用双循环方法,则需要更像这样:
for rit in rows1:
match_found = False
for git in rows2:
if (rit[1] == git[1]) and (rit[2] == git[2]):
match_found = True
break
if not match_found:
print(rit)