gpt4 book ai didi

sqlite - sqlite3是否支持循环?

转载 作者:行者123 更新时间:2023-12-03 18:25:02 24 4
gpt4 key购买 nike

我在下面编写了小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


结果是这样的:

134         1                   
136 1
139 2
159 1


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

现在我知道 sqlite3是一个非常有限的数据库,并且可能我想要的东西太复杂了。我一直在寻找它,但实际上我是一个数据库专家,到目前为止,我所获得的成功是在另一个数据库上或解决了一个完全不同的问题。

最简单的答案(我不希望BTW出现)是“ sqlite3不支持循环”。

最佳答案

SQLite不支持循环。这是entire language,您会注意到完全没有结构化编程。

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

 select measurement, count( measurement ) from errors GROUP BY measurement


这将为您提供 measurement表中所有 errors的列表以及每一个出现的频率的计数。

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

关于sqlite - sqlite3是否支持循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17889933/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com