我有这个问题:
c.execute("SELECT WPNumber, ROUTE, WPID FROM rte WHERE ROUTE = ? AND (WPID = ? OR WPID = ?) LIMIT 3", (x[1], x[0], x[2])))
查询有效,但我需要先返回WPID = x [0]的结果。换句话说,如果x [0]在表格的下方,它仍然必须作为第一个结果返回。
我已经摆弄了一下,我认为按字段排序可以完成这项工作。但是,我的SQL知识有限,我无法让查询工作。我是在正确的轨道上吗?查询会是什么样的?
答案 0 :(得分:0)
为了能够使用ORDER BY
,您需要将两个ID值转换为第一个ID保证较小的ID值。
在一般情况下,可以使用CASE expression:
c.execute("SELECT WPNumber, ROUTE, WPID" +
" FROM rte" +
" WHERE ROUTE = ? AND WPID IN (?, ?)" +
" ORDER BY CASE WPID WHEN ? THEN 1 ELSE 2 END" +
" LIMIT 3",
(x[1], x[0], x[2], x[0]))
答案 1 :(得分:-1)
你可以试试这个:
c.execute("SELECT WPNumber, ROUTE, WPID FROM rte WHERE ROUTE = ? AND (WPID = ? OR WPID = ?) ORDER BY " + X[0] + " LIMIT 3 ", (x[1], x[0], x[2])))
最后通过子句订购订单顺序 e.g。
SELECT WPNumber, ROUTE, WPID FROM rte WHERE ROUTE = "foo" AND (WPID = 11 OR WPID = 22) ORDER BY 11, 22 LIMIT 3