Totor
Totor

Reputation: 135

Merging two SQLite tables from the same database with python and sqlite3

I am trying to create a new table that combines columns from two different tables using an id column that is common to both as a keyword. 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:

id | shop | color
-------------
 1 |  11  | blue  
 2 |  34  | red   
 3 |  25  | red 

What should I write in sqlite3 to have something like this??

id | item | price | shop | color
-------------------------------
 1 | book | 20    |  11  | blue 
 2 | copy | 30    |  34  | red   
 3 | pen  | 10    |  25  | red 

Thanks!

Upvotes: 1

Views: 1768

Answers (2)

flmlopes
flmlopes

Reputation: 62

Edited: try to change the LEFT JOIN for INNER JOIN to see if it works.

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

Upvotes: 2

Ajax1234
Ajax1234

Reputation: 71451

You can use 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()

Upvotes: 1

Related Questions