Python根据另一个lis中不存在的值过滤一个列表

2024-05-14 12:34:35 发布

您现在位置:Python中文网/ 问答频道 /正文

试图用表B中找不到的2个值筛选表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]))

Tags: infromgityourpwdqueryconselect
2条回答

只需使用熟悉的LEFT JOIN... IS NULL / NOT EXISTS / NOT IN的纯SQL解决方案。下面是在MS Access中兼容的等效查询,根据col1col2返回TableA中而不是TableB中的行。在

左连接…为空

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

不存在

^{pr2}$

不在

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)

相关问题 更多 >

    热门问题