I’m trying to update a table by using join. Also one of the join is self join.
I need to update a column with the same column in the same table.
SERVICE ID code value
123 QUANTITY1 2
123 QUANTITY2 null
It should be update QUANTITY2 as "2".
UPDATE "X"."ORDER_PRODUCT" op
set op."PROPERTY_VALUE"= op2."PROPERTY_VALUE"
from "X"."ORDER_PRODUCT" op2 cross join
"X"."ORDER_PROJECT" op3
where op."SERVICE_ID"= op2."SERVICE_ID" and op."ORDER_ID" =op3."ID"
and op."PRODUCT_CODE" ='Tell_Datacenter_Co-location_Alan' and op2."PROPERTY_CODE" ='Quantity'
and op."PROPERTY_CODE"='Tell_Quantity' and op."PROPERTY_VALUE" is null
and op3."PROJECT_STATUS" not in ('ProjectWF.Cancel','ProjectWF.Complete')
Error : SQL Error [42703]: ERROR: column "op" of relation "ORDER_PRODUCT" does not exist
Position: 48
2
Answers
I would ensure that you have a way to restore this table before trying any suggested update query. Ideally we would see some sample data in your question as I’m unsure if the suggestions below are valid.
Please carefully consider the sample data I generated, see: https://dbfiddle.uk/xgucUoXX and also consider the results. This should help you refine the query before running on your data.
Assuming you can use
WITH
then the simplest way to do this is via a common table expression:nb: As at v16, the
update
command does not directly support "join" ref. but does allow multiple table references through thefrom
clause, and to then impose conditions through thewhere
clause. So this may work without usingWITH
:The error you’re getting is you are using the same table alias op for both the main table and the joined table. To fix this, you can use different table aliases for the main table and the joined table. For example, you can use op1 for the main table and op2 for the joined table.
In this updated query, I’ve used a different alias for the second instance of the "X"."ORDER_PRODUCT" table, which is necessary for the self-join to work correctly. The query should now update the "PROPERTY_VALUE" in the "X"."ORDER_PRODUCT" table as intended.