我有一個 SQLite 資料庫包含幾個表,其中一些(不是全部)有一個名為“附件”的特定列。我想知道是否有一個查詢可以從所有具有該列的表中獲取“附件”列的值。我可以從資料庫中獲取所有表的名稱,然后單獨查詢所有表。但我認為必須有一個單一的查詢來做到這一點。
uj5u.com熱心網友回復:
可以使用 SQLite 代碼將 sqlSELECT陳述句作為字串獲取并執行以獲取attachment資料庫所有表中列的所有值:
SELECT GROUP_CONCAT('SELECT ' || pti.name || ' FROM ' || sm.name, ' UNION ALL ') sql
FROM sqlite_master sm CROSS JOIN pragma_table_info(sm.name) pti
WHERE sm.type = 'table' AND pti.name = 'attachment';
上面的查詢回傳一個只有 1 行和 1 列的結果集,別名為sql這樣的字串值:
SELECT attachment FROM table1
UNION ALL
SELECT attachment FROM table2
UNION ALL
SELECT attachment FROM table4
您可以根據需要更改UNION ALL為UNION函式內部GROUP_CONCAT()。
查看簡化的演示。
uj5u.com熱心網友回復:
您可以在連接上使用GetSchema方法定義該欄位的每個表中獲取每個附件欄位的值,以查找所有相關表,然后您可以使用 sql 陳述句 UNION 在單個命令中提取所有附件值。
這應該是只使用標準 ADO.NET 命令和方法的代碼:
using(SQLiteConnection cnn = new SQLiteConnection(@"Data Source=E:\\temp\\mydb.db;Version=3"))
{
cnn.Open();
// We want all columns with the name as "attachment"
DataTable dt = cnn.GetSchema("COLUMNS", new string[] {null, null, null, "attachment"});
// Now we prepare the single commands that extract the attachments value
// from every row returned by the previous query.
// The TABLE_NAME field contains the name of the relevant table
var s = dt.AsEnumerable().Select(x => $"SELECT attachment FROM [{x.Field<string>("TABLE_NAME")}]");
// We join together the single commands separating them with the UNION statement
string command = string.Join(" UNION ", s);
// Finally we can construct and execute a command loading a datatable
// with all the attachements values from every table.
SQLiteCommand cmd = new SQLiteCommand(command, cnn);
dt = new DataTable();
dt.Load(cmd.ExecuteReader());
// Here you can work on the single field in the _dt_ table
....
}
請注意,UNION 將為每個附件提取不同的值。這意味著,如果您有兩個同名的附件,則只會列出一次。如果您想保留所有內容,請將 UNION 更改為 UNION ALL(陳述句前后有空格)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/419868.html
標籤:
