[英]Merging two SQLite tables from the same database with python and sqlite3
我正在嘗試創建一個新表,該表使用兩個關鍵字共同使用的id列來組合來自兩個不同表的列。 假設我們有一個名為db.db的數據庫,其中包含兩個名為table1和table2的表。
table1看起來像這樣:
id | item | price
-------------
1 | book | 20
2 | copy | 30
3 | pen | 10
和table2是這樣的:
id | shop | color
-------------
1 | 11 | blue
2 | 34 | red
3 | 25 | red
我應該在sqlite3中寫些什么來擁有這樣的東西?
id | item | price | shop | color
-------------------------------
1 | book | 20 | 11 | blue
2 | copy | 30 | 34 | red
3 | pen | 10 | 25 | red
謝謝!
編輯:嘗試將LEFT JOIN更改為INNER JOIN以查看其是否有效。
import sqlite3
conn = sqlite3.connect('db.db')
c = conn.cursor()
def merged():
c.execute('CREATE TABLE table3 AS SELECT * FROM table1 t1 INNER JOIN table2 t2 ON t1.id = t2.id')
for line in c.fetchall():
print(line)
merged()
您可以使用itertools.groupby
:
import itertools, sqlite3
d1 = list(sqlite3.connect('db.db').cursor().execute("SELECT id, item, price FROM table1"))
d2 = list(sqlite3.connect('db.db').cursor().execute("SELECT id, item, price FROM table2"))
full_data = sorted(d1+d2, key=lambda x:x[0])
grouped = [[a, list(b)] for a, b in itertools.groupby(full_data, key=lambda x:x[0])]
final_grouped = [[a, *[i for c in b for i in c[1:]]] for a, b in grouped]
conn = sqlite3.connect('db.db')
conn.execute('CREATE TABLE file3 (id real, item text, price real, shop real, color text)')
conn.executemany('INSERT INTO file3 VALUES (?, ?, ?, ?, ?)', final_grouped)
conn.commit()
conn.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.