简体   繁体   中英

how to insert values into a column of a table in successive rows by fetching values from a column in a row with a same id in another table

In my application, I use PostgreSQL database. I have two tables namely wc_content_definition and simple_web_content . The field web_content_definition_id is the primary key for wc_content_definition table and simple_web_content_id is the primary key for simple_web_content . I have added field in simple_web_content named web_content_definition_id and I want to fill this field in all the rows with the correct value from the wc_content_definition table. A column named web_content_id in the wc_content_definition table stores the value of simple_web_content_id for that row and I am trying to use that value to get the web_content_definition_id and insert its value in the corresponding row in the simple_web_content table. The query I am trying to use is:

update simple_web_content set web_content_definition_id = (select 
wcd.web_content_definition_id from  wc_content_definition wcd, 
simple_web_content swc where  simple_web_content_id = wcd.web_content_id ) 
and swc.simple_web_content_id <> 0 and wcd.web_content_id <> 0;

I am getting the following error:

ERROR: missing FROM-clause entry for table "swc" LINE 3: ... simple_web_content_id = wcd.web_content_id ) and swc.simple...

Error ERROR: missing FROM-clause entry for table "swc" SQL state: 42P01 Character: 209

I am using the pg-admin tool to execute the queries

update simple_web_content 
set web_content_definition_id =  wcd.web_content_definition_id
from  wc_content_definition wcd 
WHERE simple_web_content_id = wcd.web_content_id 
AND simple_web_content_id <> 0 and wcd.web_content_id <> 0;

In the query you had, the table wc_content_definition can't be referenced outside the sub-query.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM