postgresql:如何将数据从两个单独的 table 导入到单个 table 到同一行中?

postgresql: how to import data from two separate tables into a single table into the SAME row?

我正在使用 postgresql 从 single_sales_records 创建 countries table。 single_sales_records 看起来像这样:

sales_id |region                           |country| <Many other columns!>
---------------------------------------------------------------------------
1        |Australia and Oceania            |Tuvalu | ...
2        |Central America and the Caribbean|Grenada| ...
3        |Europe                           |Russia | ...
.
.

在此之前,我创建了一个regionstable,基本上是这样的:

region_id | region
-------------------------------
1         |asia
2         |australia and oceania
3         |central america and the caribbean
4         |north america
5         |sub-saharan africa
6         |middle east and north africa
7         |europe

我要创建的countries table(1个区域可以有多个国家)应该是这样的:

country_id | country | region_id
-----------------------------------------
1          |korea    |1
.
.
.

我有一个查询帮助我填充 'regions' table:

INSERT INTO regions (region)
SELECT DISTINCT region
FROM single_sales_records;

我的当前查询遇到了问题,该查询应该由 'countries' table:

填充
INSERT INTO countries (country)
SELECT DISTINCT country
FROM single_sales_records;
INSERT INTO countries (region_id)
SELECT DISTINCT region_id
FROM regions;

当我这样做时,我的 'countries' table 不匹配区域内的国家 - 而是列出所有国家,然后为区域添加 7 行。它看起来像这样:

country_id | country | region_id
-----------------------------------------
1          |korea    |null
.
.
76         |haiti    |null
77         |null     |1
.
.
83         |null     |7

谁能帮我把国家和地区匹配起来?

我试图寻找其他 so 文章,但他们正在谈论将数据插入两个单独的 table 中,或者谈论连接(我认为这不需要连接...对?)。

非常感谢! [这篇文章被编辑为包括 single_sales_records]

您想要 JOIN 表一起 INSERT:

INSERT INTO countries (region_id, country)
    SELECT DISTINCT r.region_id, country
    FROM single_sales_records ssr JOIN
         regions r
         ON ssr.region = r.region;