Reputation: 153
I am trying to do what I think should be a simple SQLite operation. I want to multiply two columns from separate tables and put the results in a new column in the first table. The following runs, but produces a column of all 0.0:
UPDATE table 1
SET columnC = (SELECT (table1.columnB * table2.columnX)
FROM table 1
INNER JOIN table2 ON table1.columnA = table2.columnA);
If I isolate the SELECT statement in parentheses and run it on its own, I get the right values, but I don't know how to insert these into a column in the table.
SELECT (table1.columnB * table2.columnX)
FROM table 1
INNER JOIN table2 ON table1.columnA = table2.columnA;
Any insight?
Upvotes: 1
Views: 779
Reputation: 56938
I think your issue might be that you aren't restricting the update so it is applying it to the every row for every row so at the end of it columnC would be the same value throughout.
e.g. Assuming :-
DROP TABLE IF EXISTS table2;
CREATE TABLE IF NOT EXISTS table2 (columnA INTEGER,columnX INTEGER);
INSERT INTO table1 VALUES(1,5,0),(2,7,0),(3,8,0),(4,3,0);
INSERT INTO table2 VALUES(1,4),(2,3),(3,10),(4,21);
SELECT * FROM table1 JOIN table2 ON table1.columnA = table2.columnA;
The result (tables unchanged, so the base data, both tables joined highlighted is table 2 columns) :-
Using (your way i.e. WHERE
's commented out) :-
UPDATE TABLE1 SET columnC =
(SELECT (table1.columnB * table2.columnX)
FROM table1
INNER JOIN table2 ON table1.columnA = table2.columnA
--WHERE table1.columnA = 3
)
--WHERE columnA = 3
;
SELECT * FROM table1 JOIN table2 ON table1.columnA = table2.columnA
The result is (all ColumnC's changed to 20 i.e. 4 * 5 as per Table1.ColumnA * Table2.ColumnX for where ColumnA's are 1) :-
WHERE
Adding the WHERE
's then the result is :-
Now if you wanted to update all rows then you could use WITH ... UPDATE e.g.
WITH updates(ID, newvalue) AS (
SELECT table1.columnA,
table1.columnB * table2.columnX
FROM table1
INNER JOIN table2 ON table1.columnA = table2.columnA
)
UPDATE TABLE1 SET columnC =
(
SELECT newvalue
FROM updates
WHERE table1.columnA = ID
)
;
Which would result in :-
Upvotes: 2