![](/img/trans.png)
[英]Python & Sqlite3 - Subset one table then join on two other tables
[英]Create new SQLite table combining column from other tables with sqlite3 and python
我正在嘗試創建一個新表,該表結合了來自兩個不同表的列。 假設我們有一個名為db.db的數據庫,其中包含兩個名為table1和table2的表。
table1看起來像這樣:
id | item | price
-------------
1 | book | 20
2 | copy | 30
3 | pen | 10
和table2這樣(注意軸重復):
id | item | color
-------------
1 | book | blue
2 | copy | red
3 | pen | red
1 | book | blue
2 | copy | red
3 | pen | red
現在,我試圖創建一個名為new_table的新表,該表在同一軸上同時組合了價格和顏色列,並且沒有重復項。 我的代碼如下(由於我的SQL技能很差,它顯然不起作用):
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("CREATE TABLE new_table (id varchar, item integer, price integer, color integer)")
cur.execute("ATTACH DATABASE 'db.db' AS other;")
cur.execute("INSERT INTO new_table (id, item, price) SELECT * FROM other.table1")
cur.execute("UPDATE new_table SET color = (SELECT color FROM other.table2 WHERE distinct(id))")
con.commit()
我知道最后一行代碼中存在多個錯誤,但我無法解決。 您將如何解決此問題? 謝謝!
就像是
CREATE TABLE new_table(id INTEGER, item TEXT, price INTEGER, color TEXT);
INSERT INTO new_table(id, item, price, color)
SELECT DISTINCT t1.id, t1.item, t1.price, t2.color
FROM table1 AS t1
JOIN table2 AS t2 ON t1.id = t2.id;
注意固定的列類型; 你的很奇怪。 項目和顏色為整數?
如果每個id值在新表中都是唯一的(只有一行的id為1,則只有2,依此類推),該列也可能也是INTEGER PRIMARY KEY
。
編輯:此外,由於您正在從基於附加文件的數據庫中的表中在內存數據庫中創建此表,也許您想要一個臨時表呢? 還是觀點可能更合適? 不確定您的目標是什么。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.