是否可以保存重复查询?

Can repeating query be saved?

在我的 Python / Sqlite 程序中,我 运行 宁这样的查询

q=SELECT COUNT(1) FROM (SELECT a1 FROM tableX WHERE freq>=1.6 AND a3='n' AND a4='y' AND a5='q' GROUP BY a1)
q=SELECT COUNT(1) FROM (SELECT a2 FROM tableX WHERE freq>=1.6 AND a3='n' AND a4='y' AND a5='q' GROUP BY a2)
q=SELECT COUNT(1) FROM (SELECT a9 FROM tableX WHERE freq>=1.6 AND a3='n' AND a4='y' AND a5='q' GROUP BY a9)

所以“基本”查询是相同的,Sqlite 收集的行也是相同的,但是由于分组不同,我不得不运行多次相同的查询。

我想知道是否有一种方法可以更有效地实现相同的输出,即。 运行只查询一次?

如果你的 q 变量是要执行的查询字符串,你可以用循环做你想做的事:

for i in [1, 2, 9]:
    q=f"SELECT COUNT(1) FROM (SELECT a{i} FROM tableX WHERE freq>=1.6 AND a3='n' AND a4='y' AND a5='q' GROUP BY a{i})"

在你的每个子查询中,虽然你使用的是 GROUP BY,但你没有进行任何聚合,所以我认为你想要的只是计算每个案例的不同 aX

您可以在单个查询中执行此操作,return所有计数器作为不同的列:

SELECT COUNT(DISTINCT a1) AS q1,
       COUNT(DISTINCT a2) AS q2,
       COUNT(DISTINCT a9) AS q9
FROM tableX
WHERE freq >= 1.6 AND a3 = 'n' AND a4 = 'y' AND a5 = 'q';