首页 文章

仅使用postgres中的文本文件匹配id来更新表

提问于
浏览
-2

我们在postgres数据库中有如下表格

id   resourceid   name         uuid
101  103          RHQ Agent    5422a14f-b68d-4a44-8de6-c1779eeec1f3
108  107          Stable env   01bd63cd-23cb-4c2e-8ae3-ec1c6e1971bb
103  115          kb tier      01bd63cd-23cb-4c2e-8ae3-ec1c6e1971cc
102  104          JON Server   95f0d1b3-ff5f-46fa-95ac-09425db933b2

其中有100多条记录

**We have text file as**

id        name

101      JON Agent

102      unstable env

预期产量:

**id   resourceid   name              uuid**

101    103          JON Agent         5422a14f-b68d-4a44-8de6-c1779eeec1f3

108    107          unstable env      01bd63cd-23cb-4c2e-8ae3-ec1c6e1971bb

102    104          Jboss Server      95f0d1b3-ff5f-46fa-95ac-09425db933b2

要求:

我们需要使用GUI(JON监视工具)更改资源的名称,因为它有许多资源我们决定通过直接在数据库中更新名称来完成它 .

通过使用JON cli,我们获取了每个资源名称的ID,因此我们的文本文件将具有需要如上所述进行更改的 ID and NAMES .

我们需要使用我们的文本文件更新表(column = name),仅用于匹配id(只有'name'列应该更改而不是其他列),正如我在预期输出中提到的那样 .

超过100条记录需要更新 . 请帮忙解决这个问题 .

1 回答

  • 2

    如果您要做的只是使用文本文件中的数据更新现有表中的字段,则使用SQL(无需GUI)非常简单:

    -- Create a table to store data from the text file
    CREATE TABLE import_data (id INT, name TEXT);
    
    -- Import the data to the new table
    COPY import_data FROM '/path/to/my/textfile.txt' CSV HEADER DELIMITER E'\t';
    
    -- Update the existing table with the names from the imported data, using id to match
    UPDATE my_table
    SET name = import_data.name
    FROM import_data
    WHERE my_table.id = import_data.id;
    
    -- Drop the import data table
    DROP TABLE import_data;
    

    如果您的文本文件使用不同的分隔符或有引号,请参阅:https://www.postgresql.org/docs/current/static/sql-copy.html

相关问题