【问题标题】:How do i copy the columns from a table and insert it into another table with a sequenced column?(PostgreSQ如何从表中复制列并将其插入到另一个带有亮片列的表中?(PostgreSQL
【发布时间】:2017-04-01 12:41:08
【问题描述】:

我有一个名为 test_pois 的表,我想将列 code 和 fclass 复制到表 test_fclass 上的列中。

但问题是,表 test_fclass 有一个名为 fid 的列,它是一个序列列。所以我只想要一次复制的列。我正在使用 PostgreSQL。我怎么能意识到呢?我想写一个函数,但也许有更简单的方法。

最后,我想在表 test_pois 上创建一个外键,它将 2 列减少为 1 列,并带有一个 id。

也许你会说,通过写一些插入来实现,但是里面有很多数据。

我使用以下 insert into 语句从 test_pois 表中复制数据:

insert into test_fclass (fcode, fclass) select code, fclass from test_pois;

输出:

如您所见,ID 4-7 分配给代码 2907。但我想要代码 2907 的唯一 ID。

【问题讨论】:

  • 请阅读meta.stackoverflow.com/questions/285551/… 和接受的答案
  • edit 您的问题并根据您的示例数据添加预期输出。 Formatted textno screen shots
  • 为什么“排序”列会出现问题?而且,这是否意味着serial 列?
  • 简单的insert into test_fclass (code, fclass) select code, fclass from test_pois;怎么样
  • 是的,它是一个连续的专栏。问题是有不止一行具有相同的 fclass 和 fcode 但我想要我的表 test_fclass 上的一些唯一数据。

标签: database postgresql function


【解决方案1】:

我是用 plpgsql 函数实现的。

    CREATE or replace FUNCTION populate() RETURNS void AS $$
DECLARE
    anzahl integer;
    zahl integer;
    zahl2 integer;
    text varchar(20);
    count integer;
    varcode smallint;
    var integer;
    varclass character varying(20);
    curse CURSOR FOR SELECT fcode FROM fclass;

    poiscurse cursor for select code from test_pois;
BEGIN

var := 0;
anzahl:= 0;
zahl := 0;
for v_anzahl in poiscurse
loop

var := var +1;
--raise notice '%',var;
text := v_anzahl::text;
SELECT substring(text FROM '[0-9]+') into zahl;
select code,fclass into varcode,varclass
from test_pois
where code = zahl;
if var = 1 then
insert into fclass (fcode, fclass) values (varcode,varclass);
raise notice '% and % inserted',varcode,varclass;
end if;
anzahl := 0;
for v_zahl in curse
loop
text := v_zahl::text;
SELECT substring(text FROM '[0-9]+') into zahl2;
if zahl = zahl2 then
anzahl := anzahl +1;
exit;
end if;
end loop;
if anzahl = 0 then
insert into fclass (fcode, fclass) values (varcode,varclass);
raise notice '% und % eingefügt',varcode,varclass;
end if;
end loop;
end;

$$ LANGUAGE plpgsql

还有输出:

顺便谢谢你的回答。

【讨论】:

    猜你喜欢
    • 2021-08-25
    • 2019-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多