Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python sqlite fetchmany和fetchall返回有序结果_Python_Sqlite_Fetchall - Fatal编程技术网

Python sqlite fetchmany和fetchall返回有序结果

Python sqlite fetchmany和fetchall返回有序结果,python,sqlite,fetchall,Python,Sqlite,Fetchall,我注意到Python sqlite fetchall()和fetchmany()语句以排序键顺序而不是原始键顺序返回结果。例如,考虑: list_indexes = [9, 5, 2, 8, 3, 7] indexsize = len(list_indexes) cursor.arraysize = indexsize cursor.execute("select index, details from this_table where index in (%s)" % ','.join('

我注意到Python sqlite fetchall()和fetchmany()语句以排序键顺序而不是原始键顺序返回结果。例如,考虑:

list_indexes = [9, 5, 2, 8, 3, 7]

indexsize = len(list_indexes)
cursor.arraysize = indexsize

cursor.execute("select index, details from this_table where index in (%s)" % ','.join('?' * len(list_indexes)), list_indexes)
rows = cursor.fetchmany(indexsize)
返回的行顺序是按键顺序排序的[2,3,5,7,8,9]


我是否遗漏了什么,或者这是默认行为?如果是这样的话,除了按参数索引对行重新排序这一显而易见的方法外,还有其他解决方法吗?

这是正常的行为。除非在查询中指定了排序依据,否则结果中的行顺序是未定义的。如果您有一些字段可用于排序(例如日期),则应该使用它

您可以使用临时表来执行以下操作:

; prepare test table
CREATE TABLE this_table (`index` INTEGER, record_details TEXT);
INSERT INTO this_table VALUES (1, 'a1');
INSERT INTO this_table VALUES (2, 'a2');
; ...
INSERT INTO this_table VALUES (10, 'a10');

; do the query
CREATE TEMP TABLE good_indexes(number INTEGER, i integer);
INSERT INTO good_indexes(number, i) VALUES (1, 4);
INSERT INTO good_indexes(number, i) VALUES (2, 2);
INSERT INTO good_indexes(number, i) VALUES (3, 6);

SELECT record_details FROM this_table, good_indexes 
WHERE good_indexes.i = this_table.`index` ORDER BY good_indexes.number;
; result: a4, a2, a6

DROP TABLE good_indexes;

谢谢你的澄清。作为一种解决方法,使用参数索引对行重新排序更容易。