【问题标题】:Create new SQLite table combining column from other tables with sqlite3 and python使用 sqlite3 和 python 创建新的 SQLite 表,将其他表中的列组合起来
【发布时间】:2018-10-11 19:41:19
【问题描述】:

我正在尝试创建一个将两个不同表中的列组合在一起的新表。 假设我有一个名为 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()

我知道最后一行代码中有多个错误,但我无法理解它。您对这个问题的处理方法是什么?谢谢!

【问题讨论】:

    标签: python sql sqlite


    【解决方案1】:

    类似

    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

    编辑:另外,由于您是在内存数据库中从附加的基于文件的数据库中的表中创建此表...也许您想要一个临时表来代替?或者观点可能更合适?不知道你的目标是什么。

    【讨论】:

      猜你喜欢
      • 2015-05-10
      • 2022-08-16
      • 1970-01-01
      • 2018-05-05
      • 2016-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多