【发布时间】:2012-04-26 15:24:09
【问题描述】:
我有一个从两个内部连接表中进行选择的 sql 查询。 select 语句的执行大约需要 50 秒。但是, fetchall() 需要 788 秒,并且只获取 981 个结果。这是查询和fetchall代码:
time0 = time.time()
self.cursor.execute("SELECT spectrum_id, feature_table_id "+
"FROM spectrum AS s "+
"INNER JOIN feature AS f "+
"ON f.msrun_msrun_id = s.msrun_msrun_id "+
"INNER JOIN (SELECT feature_feature_table_id, min(rt) AS rtMin, max(rt) AS rtMax, min(mz) AS mzMin, max(mz) as mzMax "+
"FROM convexhull GROUP BY feature_feature_table_id) AS t "+
"ON t.feature_feature_table_id = f.feature_table_id "+
"WHERE s.msrun_msrun_id = ? "+
"AND s.scan_start_time >= t.rtMin "+
"AND s.scan_start_time <= t.rtMax "+
"AND base_peak_mz >= t.mzMin "+
"AND base_peak_mz <= t.mzMax", spectrumFeature_InputValues)
print 'query took:',time.time()-time0,'seconds'
time0 = time.time()
spectrumAndFeature_ids = self.cursor.fetchall()
print time.time()-time0,'seconds since to fetchall'
fetchall 需要这么长时间有什么原因吗?
更新
在做:
while 1:
info = self.cursor.fetchone()
if info:
<do something>
else:
break
和
一样慢allInfo = self.cursor.fetchall()
for info in allInfo:
<do something>
【问题讨论】:
-
我会尝试将尽可能多的严格等式约束移到
INNER JOIN的ON子句中,因为这将(希望)最小化到达@987654326 的堆大小@ 部分(不等式通常会被加载到内存中以进行完整的堆扫描,此时您的时间尺度由堆大小而不是索引决定——这很烦人,可能不直观,但由于不等式查询的不确定性,这在很大程度上是不可避免的结果大小)。
标签: performance sqlite fetchall