【问题标题】:How to compare 2 columns of different tables?如何比较不同表的 2 列?
【发布时间】:2019-09-25 01:29:46
【问题描述】:

我需要使用 csv 文件填充数据库。外键实现为xid REFERENCES table1 NOT NULL。现在我需要用第一个表中的cid 在第二个表中填充xid

表格是这样设置的

table1:

xid SERIAL Primary KEY
country VARCHAR(256)

table2:

yid SERIAL Primary KEY 
building VARCHAR(256)
country VARCHAR(256)
xid REFERENCES country NOT NULL

我使用 csv 文件填充了 table1。现在我的问题是我无法将xid 转换为table2。 我正在使用带有import csvimport psycopg2 的python

【问题讨论】:

    标签: python database postgresql csv psycopg2


    【解决方案1】:

    我建议创建一个临时表来加载数据:

    CREATE TEMPORARY TABLE temp_building (building VARCHAR(256), country VARCHAR(256)) ON COMMIT DROP;
    

    将您的数据加载到这个临时表中,然后加载 table2:

    INSERT INTO table2 (building, country, xid)
    SELECT building, country, xid
    FROM table2
    JOIN temp_building on temp_building.country = table2.country;
    

    然后,提交您的事务,临时表将被删除。

    但是,我强烈建议不要将国家/地区列放入表 2。数据已经在table1中,请勿重复。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多