2014-01-28 25 views
1

我有相同的架構多個SQLite數據庫,我想他們都合併在一起,因爲我有一個唯一的列,有可能是重複的風險,我使用insert or ignore,SQLite中它會很容易:使用bash合併多個SQLite數據庫?

sqlite3 database.db3 
sqlite> attach './db1.db3' as s1; 
sqlite> attach './db2.db3' as s2; 
sqlite> attach './db3.db3' as s3; 
sqlite> insert or ignore into table (c1, c2, c3) select c1, c2, c3 from s1.table; 
sqlite> insert or ignore into table (c1, c2, c3) select c1, c2, c3 from s2.table; 
sqlite> insert or ignore into table (c1, c2, c3) select c1, c2, c3 from s3.table; 
sqlite> .exit 

我讀了關於轉儲,但我不想合併整個架構,只有一個表,所以我想這個解決方案,現在直到這裏一切都很好,但我需要通過bash運行所有這一切,我嘗試了以下但它不:

sqlite3 database.db3 "attach './db1.db3' as s1;" 
sqlite3 database.db3 "attach './db2.db3' as s2;" 
sqlite3 database.db3 "attach './db3.db3' as s3;" 
sqlite3 database.db3 "select count(*) from s1.table;" 
sqlite3 database.db3 "select count(*) from s2.table;" 
sqlite3 database.db3 "select count(*) from s3.table;" 

它說:Error: no such table: s1.table

我在做什麼錯

回答

5

使用heredoc如下圖所示:

sqlite3 database.db3 << "EOF" 
attach './db1.db3' as s1; 
attach './db2.db3' as s2; 
attach './db3.db3' as s3; 
insert or ignore into table (c1, c2, c3) select c1, c2, c3 from s1.table; 
insert or ignore into table (c1, c2, c3) select c1, c2, c3 from s2.table; 
insert or ignore into table (c1, c2, c3) select c1, c2, c3 from s3.table; 
.exit 
EOF 

或者,把你的所有命令到一個文件中,並像這樣運行:

sqlite3 database.db3 < commandsFile 
3

1 )用你想輸入到sqlite命令行程序的行創建一個文本文件,如下所示:

attach './db1.db3' as s1; 
attach './db2.db3' as s2; 
attach './db3.db3' as s3; 
insert or ignore into table (c1, c2, c3) select c1, c2, c3 from s1.table; 
insert or ignore into table (c1, c2, c3) select c1, c2, c3 from s2.table; 
insert or ignore into table (c1, c2, c3) select c1, c2, c3 from s3.table; 
.exit 

,然後只是調用使用殼

#!/bin/bash 

sqlite3 database.db <<"EOF" 
attach './db1.db3' as s1; 
attach './db2.db3' as s2; 
attach './db3.db3' as s3; 
insert or ignore into table (c1, c2, c3) select c1, c2, c3 from s1.table; 
insert or ignore into table (c1, c2, c3) select c1, c2, c3 from s2.table; 
insert or ignore into table (c1, c2, c3) select c1, c2, c3 from s3.table; 
.exit 
EOF 
sqlite3 database.db < commands.txt

2)