1

我有这个查询:

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 知识有限,无法使查询正常工作。我在正确的轨道上吗?查询会是什么样子?

4

2 回答 2

0

为了能够使用ORDER BY,您需要将两个 ID 值转换为保证第一个 ID 较小的值。在一般情况下,这可以通过CASE 表达式来实现:

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]))
于 2013-10-04T11:46:13.167 回答
-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])))

最后按子句顺序排序,例如

SELECT WPNumber, ROUTE, WPID FROM rte WHERE ROUTE = "foo" AND (WPID = 11 OR WPID = 22) ORDER BY 11, 22 LIMIT 3

于 2013-10-04T11:12:23.747 回答