2013-07-26 103 views
0

我寫了下面的小bash腳本,它按預期工作,但我添加了一些註釋和換行代碼,以便讀取代碼。刪除註釋和換行應該使其成爲有效的腳本。`sqlite3`支持循環嗎?

### 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 -loop到SQL語句?換句話說,sqlite3是否支持某種for -loop循環查看先前查詢的結果?

現在我知道sqlite3是一個非常有限的數據庫,可能是我想要的只是太複雜了。我一直在尋找,因爲它,但我真的是一個數據庫nitwit,到目前爲止我得到的結果要麼在不同的數據庫上,要麼解決完全不同的問題。

最簡單的答案(我不希望順便說一句)是'sqlite3不支持循環'。

回答

3

SQLite不支持循環。這裏是entire language,你會注意到結構化程序完全沒有。

但是,這並不是說你不能得到你想要的,沒有循環,使用集合或其他SQL構造。你的情況可能是簡單的:

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

這會給你所有measurement S在errors表的列表和頻率每一個發生的計數。

通常,通過在單個(有時是複雜的)SQL語句中表達您的查詢來最好地利用SQL引擎,該語句被提交給引擎進行優化。在你的例子中,你已經編寫了關於從數據庫獲取數據的策略的一些決定 - 這是SQL的一個信條,引擎比程序員能夠更好地做出這些決定。

+0

這似乎工作!我沒有意識到我可以將'GROUP'與count()結合使用。我非常習慣於把東西拼湊在一起,因此我的小腳本。 – jippie