Create new SQLite table combining column from other tables with sqlite3 and python

I am trying to create a new table that combines columns from two different tables. Let's imagine then that I have a database named db.db that includes two tables named table1 and table2.

table1 looks like this:

id | item | price
-------------
 1 | book | 20  
 2 | copy | 30   
 3 | pen  | 10 

and table2 like this (note that has duplicated axis):

id | item | color
-------------
 1 | book | blue  
 2 | copy | red   
 3 | pen  | red 
 1 | book | blue  
 2 | copy | red   
 3 | pen  | red 

Now I'm trying to create a new table named new_table that combines both columns price and color over the same axis and also without duplicates. My code is the following (it does not obviously work because of my poor SQL skills):

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()

I know there are multiple errors in the last line of code but I can't get my head around it. What would be your approach to this problem? Thanks!

1 answer

  • answered 2018-10-11 19:49 Shawn

    Something like

    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;
    

    Note the fixed column types; yours were all sorts of strange. item and color as integers?

    If each id value is unique in the new table (Only one row will ever have an id of 1, only will be 2, and so on), that column should probably be an INTEGER PRIMARY KEY, too.

    EDIT: Also, since you're creating this table in an in-memory database from tables from an attached file-based database... maybe you want a temporary table instead? Or a view might be more appropriate? Not sure what your goal is.