我正在使用此查询来验证2个航路点(x [0]和x [2])是否在给定路线上:
c.execute("SELECT WPNumber, ROUTE, WPID FROM wpnavrte WHERE ROUTE = ? AND (WPID = ? OR WPID = ?)", (x[1], x[0], x[2]))
如果两条航路点都在路线上,则结果应为[('001', 'A123', 'WAYPOINT X'), ('005', 'A123', 'WAYPOINT Y')]
如果航点/航线组合为假,它将返回“无”或一个列表。
检查查询结果是否为双重列表(或不是)的最pythonic方法是什么?
答案 0 :(得分:1)
c.execute("""SELECT t1.WPNumber, t1.ROUTE, t1.WPID, t2.WPID
FROM wpnavrte t1
JOIN wpnavrte t2
ON t1.ROUTE = t2.ROUTE
WHERE t1.ROUTE = ? AND t1.WPID = ? AND t2.WPID = ?
""", (x[1], x[0], x[2]))
如果两个航点在同一航线上,那么c.fetchone()
将返回一个4元组,其值代表WPNumber,Route,第一和第二个WPID。
如果两个航点不在同一航线上,c.fetchone()
将返回None
。
答案 1 :(得分:1)
也许最简单的是稍微修改你的SQL查询(应用LIMIT 3
来减轻查询,然后检查你只有2):
results = list(c.execute("SELECT WPNumber, ROUTE, WPID FROM wpnavrte WHERE ROUTE = ? AND (WPID = ? OR WPID = ?) LIMIT 3", (x[1], x[0], x[2])))
if len(results) != 2:
# do something