Python和SQLite3:查询必须返回2个列表

时间:2013-10-03 10:20:34

标签: python list python-3.x sqlite

我正在使用此查询来验证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方法是什么?

2 个答案:

答案 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