带有动态值的Sql插入

时间:2015-01-12 06:41:39

标签: sql postgresql

我在postgres数据库上使用以下查询:

insert into user_settings (google_access_token, google_refresh_token) 
   select 'google_access_token', 'google_refresh_token' from user 
   where id = user_id

table user_settings有一个字段user_id,对应于用户表中名为id的字段。但这会给出错误:

column "user_id" does not exist 
Hint: There is a column named "user_id" in table "user_settings", 
but it cannot be referenced from this part of the query

3 个答案:

答案 0 :(得分:0)

我想你需要这样做:

   insert into user_settings (google_access_token, google_refresh_token) 
   select 'google_access_token', 
          'google_refresh_token' 
   from user 
   where id in (select user_id from user_settings )

答案 1 :(得分:0)

您正在使用user_settings中的列并使用条件插入该表。 我认为您必须使用update语句,因为您的条件是

user .id = user_settings .user_id

答案 2 :(得分:0)

即使您没有匹配的值,也可以使用NULL更新表

update user_settings
set 
user_settings.google_access_token='google_access_token',
user_settings.google_refresh_token='google_refresh_token'
from user_settings
inner join user 
on user_settings.user_id=user.id