我想从大型数据库中执行随机样本,我希望这些样本配对,这意味着我要么关心(一系列)select语句的结果顺序还是重新排序然后。此外,也可能存在重复的行。这很好,但我想要一种有效的方法直接从数据库中生成这些样本。我理解SELECT语句不能与cursor.executemany一起使用,但实际上这就是我想要的。
有一个类似的问题here OP似乎要求多选,但它对当前最高答案感到满意,这表明在where子句中使用IN。这不是我真正想要的。我更喜欢更像ken.ganong的解决方案,但想知道它的效率。
更准确地说,我做了类似以下的事情:
import sqlite3
import numpy as np
# create the database and inject some values
values = [
(1, "Hannibal Smith", "Command"),
(2, "The Faceman", "Charm"),
(3, "Murdock", "Pilot"),
(4, "B.A. Baracas", "Muscle")]
con = sqlite3.connect('/tmp/test.db')
cur = con.cursor()
cur.execute(
'CREATE TABLE a_team (tid INTEGER PRIMARY KEY, name TEXT, role TEXT)')
con.commit()
cur.executemany('INSERT INTO a_team VALUES(?, ?, ?)', values)
con.commit()
# now let's say that I have these pairs of values I want to select role's for
tid_pairs = np.array([(1,2), (1,3), (2,1), (4,3), (3,4), (4,3)])
# what I currently do is run multiple selects, insert into a running
# list and then numpy.array and reshape the result
out_roles = []
select_query = "SELECT role FROM a_team WHERE tid = ?"
for tid in tid_pairs.flatten():
cur.execute(select_query, (tid,))
out_roles.append(cur.fetchall()[0][0])
#
role_pairs = np.array(out_roles).reshape(tid_pairs.shape)
对我而言,似乎必须有一种更有效的方法将SELECT语句传递给db,db请求多个行,每个行都有自己的约束,但正如我所说,executemany不能与SELECT语句一起使用。另一种方法是在WHERE子句中使用IN约束,然后在python中创建重复项。
还有一些额外的约束,例如,我可能在数据库中有不存在的行,我可能想通过删除输出对或替换为默认值来处理它,但这些都是一个副作用
提前致谢。