- Sep 10, 2001
- 11,711
- 8
- 81
I would like to have a query which UPDATEs rows with the results of a query based on a condition.
Example:
Here is table "test_parent":
...test_id...|...result...|
......1........|....NULL...|
......2........|....NULL...|
......3........|....NULL....|
Here is table "test_child": (test_parent to test_child is a one-to-many relationship)
...test_id...|...num1...|...num2...|
......1........|.....2.......|......3.......|
......1........|......1......|......4.......|
......2........|......4......|......3.......|
......3........|......3......|.......3......|
......3........|......2......|......4.......|
......3........|......2......|.......2......|
I want to have one query that would update the column "result" with the result of the calculation (num1 * num2) of the table test_child where the column test_id matches
here's what I thought would work:
UPDATE test_parent SET result =
(SELECT sum(num1 * num2) FROM test_child tc WHERE tc.test_id = test_id)
WHERE test_id IN (1,2,3)
That last WHERE clause with the IN statement is also required because when I run this query on the real system I also need to limit to calc to certain IDs...
My query above is FAIL - it updates each row with the TOTAL calculation of num1*num2 for EVERY row in test_child. So in this case, each result column in test_parent is set to 43, but the desired result is that result for test_id 1 should be 10, for test_id 2 result should be 12 and test_id 3 is 21
Any idea how to get this to work properly?
Example:
Here is table "test_parent":
...test_id...|...result...|
......1........|....NULL...|
......2........|....NULL...|
......3........|....NULL....|
Here is table "test_child": (test_parent to test_child is a one-to-many relationship)
...test_id...|...num1...|...num2...|
......1........|.....2.......|......3.......|
......1........|......1......|......4.......|
......2........|......4......|......3.......|
......3........|......3......|.......3......|
......3........|......2......|......4.......|
......3........|......2......|.......2......|
I want to have one query that would update the column "result" with the result of the calculation (num1 * num2) of the table test_child where the column test_id matches
here's what I thought would work:
UPDATE test_parent SET result =
(SELECT sum(num1 * num2) FROM test_child tc WHERE tc.test_id = test_id)
WHERE test_id IN (1,2,3)
That last WHERE clause with the IN statement is also required because when I run this query on the real system I also need to limit to calc to certain IDs...
My query above is FAIL - it updates each row with the TOTAL calculation of num1*num2 for EVERY row in test_child. So in this case, each result column in test_parent is set to 43, but the desired result is that result for test_id 1 should be 10, for test_id 2 result should be 12 and test_id 3 is 21
Any idea how to get this to work properly?
