`sqlite3`是否支持循环?

jip*_*pie 1 sqlite

我在下面编写了一个小bash脚本,它按预期工作,但我添加了几个注释和换行符,以便于阅读,从而破坏了代码.删除注释和换行符应该使其成为有效的脚本.

### read all measurements from the database and list each value only once
sqlite3 -init /tmp/timeout /tmp/testje.sqlite \
  'select distinct measurement from errors order by measurement;' |

### remove the first line of stdout as this is a notification rather than intended output
sed '1d' |

### loop though all found values
while read error; do 

  ### count the number of occurences in the original table and print that
  sqlite3 -init /tmp/timeout /tmp/testje.sqlite \
    "select $error,count( measurement ) from errors where measurement = '$error' ;"
done
Run Code Online (Sandbox Code Playgroud)

结果是这样的:

134         1                   
136         1                   
139         2                   
159         1
Run Code Online (Sandbox Code Playgroud)

问题:是否可以sqlite3while-loop 转换为SQL语句?换句话说,sqlite3是否支持某种for循环来循环查看先前查询的结果?

现在我知道这sqlite3是一个非常有限的数据库,很有可能我想要的东西太复杂了.我一直在寻找,但是我真的是一个数据库笨蛋,到目前为止我得到的点击是在不同的数据库或解决一个完全不同的问题.

最简单的答案(我不希望BTW)是'sqlite3不支持循环'.

Lar*_*tig 6

SQLite不支持循环.这是整个语言,您会注意到结构化编程完全不存在.

但是,这并不是说你不能在没有循环的情况下获得你想要的东西,而是使用集合或其他一些SQL结构.在您的情况下,它可能很简单:

 select measurement, count( measurement ) from errors GROUP BY measurement
Run Code Online (Sandbox Code Playgroud)

这将为您提供表中所有measurements 的列表以及每个s errors发生频率的计数.

通常,最好使用SQL引擎,在单个(有时是复杂的)SQL语句中表达您的查询,该语句将提交给引擎进行优化.在您的示例中,您已经编写了一些关于用于从数据库获取数据的策略的决策 - 这是SQL的一个原则,引擎比程序员更能够做出这些决策.