有一個包含多個表的資料庫。有沒有辦法列印出包含與客戶相關的列的表名,例如:customer_ID?
我需要做的是:有兩個名為“payment”和“customer”的表,其中包含“customer_ID”列,因此必須列印“payment”和“customer”表的名稱。
uj5u.com熱心網友回復:
您可以exists與子查詢一起使用:
select m.name from sqlite_master m where m.type = 'table' and exists
(select 1 from pragma_table_info(m.name) m1 where m1.name = 'customer_ID')
import sqlite3
conn = sqlite3.connect('test_db.db')
r = list(conn.cursor().execute('''select m.name from sqlite_master m where m.type = 'table' and exists
(select 1 from pragma_table_info(m.name) m1 where m1.name = 'customer_ID')'''))
uj5u.com熱心網友回復:
這是一個自定義生成器函式,用于獲取至少包含一個給定列名的表:
def getTableNames(path, cols):
con = sqlite3.connect(path)
for (tableName, ) in con.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall():
if any(col for col in [fields[1] for fields in con.execute(f"PRAGMA table_info({tableName})").fetchall()] if
col in cols):
yield tableName
然后呼叫:
>>> list(getTableNames(path, ['customer_ID']))
這個想法是首先獲取表的串列,然后獲取存在于 sqlite 中的任何表的所有列,然后從給定的列串列中過濾出包含任何列的表。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/368719.html
