如何获得以下查询所期望的结果,目前在postgres enter link description here中不支持,(请参阅上一节兼容性部分)
UPDATE帐户SET(contact_last_name,contact_first_name)= (SELECT last_name,first_name FROM salesmen sales在哪里salesmen.id = accounts.sales_id);
实际上我正在向表中添加一个新的空列,并用另一个表/视图中相同大小和类型的列的内容填充它
do $$DECLARE
k record;
_current_view text := '';
_current_var text := '';
_new_column_sql text := '';
_insert_sql text := '';
_select_sql text := '';
begin
for k in SELECT column_name from information_schema.columns where table_name='train'
and column_name <> 'action'
loop
_current_view := 'av_' || k.column_name;
_current_var := k.column_name;
_new_column_sql := 'alter table train_average_imputed add column ' || _current_var || ' float';
_select_sql := 'select prob as ' || _current_var || ' from ' || _current_view || ', train
where train.' || _current_var || '=' || _current_view || '.' || _current_var ;
_insert_sql := 'insert into train_average_imputed(' || _current_var || ') ' || _select_sql;
raise notice '%', _select_sql;
--EXECUTE _test_sql;
EXECUTE _new_column_sql;
EXECUTE _insert_sql;
exit;
end loop;
end$$;
感谢。
更新
实际上我需要沿着行号更新,我尝试使用这个
drop table play2;
create table play2 as (select action from play);
alter table play2 add column color text;
with trans_table as(select color, row_number() over() as rn from play2)
update trans_table set color = a.color from (
select color, row_number() over() as rn from play) as a
where trans_table.rn =a.rn;
但是我收到了以下错误
DROP TABLE
SELECT 100
ALTER TABLE
ERROR: relation "trans_table" does not exist
LINE 2: update trans_table set color = a.color from (
^
我看不到我的代码与postgres with
页enter link description here的奇怪之处。请注意,如果我在select
之后使用update
而不是with
查询,则会返回预期结果。
更新2
正如Igor建议的那样,只需要复制表并从那里添加列。
答案 0 :(得分:3)
UPDATE accounts
SET (contact_last_name, contact_first_name) = (SELECT last_name, first_name FROM salesmen WHERE salesmen.id = accounts.sales_id);
可以用Postgres编写:
UPDATE accounts
SET contact_last_name = salesmen.last_name,
contact_first_name = salesmen.first_name
FROM salesmen
WHERE salesmen.id = accounts.sales_id;