I am trying to add a column from a table2 to my existing table1.
table1 looks like this (this is a 2 columns example but in reality I have more than 100):
id | item | price
-------------
1 | book | 20
2 | copy | 30
3 | pen | 10
and table2 like this:
id | item
----------
1 | book
2 | copy
3 | pen
I would like to get this:
id | item | price | item
---------------------
1 | book | 20 | book
2 | copy | 30 | copy
3 | pen | 10 | pen
However, I'm getting the following, all the same first row value:
id | item | price | item
---------------------
1 | book | 20 | book
2 | copy | 30 | book
3 | pen | 10 | book
What I am doing wrong in my code?
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("ALTER TABLE table1 ADD COLUMN item text")
cur.execute("UPDATE table1 SET item = (SELECT item FROM table2 WHERE table2.id = id)")
Thanks!
You need a correlated subquery:
UPDATE table1
SET item = (SELECT t2.item FROM table2 t2 WHERE t2.id = table1.id);
I am surprised that your version is not returning an error. The WHERE
condition is interpreted as WHERE table2.id = table2.id
, which means that all rows should be returned.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.