在INSERT INTO ...上添加LEFT JOIN ...

时间:2019-12-08 04:09:38

标签: sql postgresql

我的查询插入一个值并返回插入的新行

log_those_columns <- function(D,old_names,new_names) 
DT[,(new_names) := lapply(mget(old_names),log)]
log_those_columns(DT,old_names,new_names)
DT
     Ozone Solar.R Wind Temp Month Day New_Ozone New_Wind
  1:    41     190  7.4   67     5   1  3.713572 2.001480
  2:    36     118  8.0   72     5   2  3.583519 2.079442
  3:    12     149 12.6   74     5   3  2.484907 2.533697
  4:    18     313 11.5   62     5   4  2.890372 2.442347
  5:    NA      NA 14.3   56     5   5        NA 2.660260
 ---                                                     

我想将created_by与用户表中的user_id关联起来。

INSERT INTO 
     event_comments(date_posted, e_id, created_by, parent_id, body, num_likes, thread_id)
     VALUES(1575770277, 1, '9e028aaa-d265-4e27-9528-30858ed8c13d', 9, 'December 7th', 0, 'zRfs2I')

 RETURNING comment_id, date_posted, e_id, created_by, parent_id, body, num_likes, thread_id

是否可以将新的返回行与另一个表行连接起来?

2 个答案:

答案 0 :(得分:0)

考虑使用WITH结构将数据从插入内容传递到查询,然后可以进行查询。

示例:

-- Setup some initial tables
create table colors (
    id SERIAL primary key,
    color VARCHAR UNIQUE
);

create table animals (
    id SERIAL primary key,
    a_id INTEGER references colors(id),
    animal VARCHAR UNIQUE
);

-- provide some initial data in colors
insert into colors (color) values ('red'), ('green'), ('blue');

-- Store returned data in inserted_animal for use in next query
with inserted_animal as (
    -- Insert a new record into animals
    insert into animals (a_id, animal) values (3, 'fish') returning *
) select * from inserted_animal 
     left join colors on inserted_animal.a_id = colors.id;

-- Output
-- id | a_id | animal | id | color
-- 1  | 3    | fish   | 3  | blue

说明: WITH查询允许从初始查询返回的记录(包括从RETURNING子句返回的数据)存储在临时表中,该表可以在其后的表达式中进行访问,以继续处理该表,包括使用JOIN表达式。 / p>

答案 1 :(得分:0)

你是对的,我误会了

这应该做到:

DECLARE mycreated_by event_comments.created_by%TYPE;

INSERT INTO 
     event_comments(date_posted, e_id, created_by, parent_id, body, num_likes, thread_id)
     VALUES(1575770277, 1, '9e028aaa-d265-4e27-9528-30858ed8c13d', 9, 'December 7th', 0, 'zRfs2I')

 RETURNING created_by into mycreated_by 

SELECT * from users WHERE user_id = mycreated_by